Upgrade lz4 to v1.10.0

This project was upgraded with external_updater.
Usage: tools/external_updater/updater.sh update external/lz4
For more info, check https://cs.android.com/android/platform/superproject/main/+/main:tools/external_updater/README.md

Test: TreeHugger
Change-Id: I15d44917fb2b4421950dcd54625ca23dbfc3ec5e
diff --git a/.circleci/config.yml b/.circleci/config.yml
index ae5aa39..f1ac6c0 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -43,26 +43,26 @@
     # Test
     #   This would typically be a build job when using workflows, possibly combined with build
     # This is based on your 1.0 configuration file or project settings
-    - run: CFLAGS= make clangtest && make clean
-    - run: g++ -v; make cxxtest   && make clean
-    - run: gcc -v; g++ -v; make ctocpptest && make clean
+    - run: CC=clang CFLAGS="-Werror -O0" make all && make clean
+    - run: c++ -v; make cxxtest      && make clean
+    - run: cc -v; c++ -v; make ctocxxtest && make clean
     - run: gcc-5 -v; CC=gcc-5 CFLAGS="-O2 -Werror" make check && make clean
     - run: gcc-5 -v; CC=gcc-5 CFLAGS="-O2 -m32 -Werror" CPPFLAGS=-I/usr/include/x86_64-linux-gnu make check && make clean
-    - run: gcc-6 -v; CC=gcc-6 MOREFLAGS="-O2 -Werror" make check  && make clean
-    - run: make cmake               && make clean
+    - run: gcc-6 -v; CC=gcc-6 CFLAGS="-O2 -Werror" make check  && make clean
+    - run: make cmakebuild           && make clean
     - run: make -C tests test-lz4
     - run: make -C tests test-lz4c
     - run: make -C tests test-frametest
     - run: make -C tests test-fuzzer && make clean
-    - run: make -C lib all          && make clean
-    - run: pyenv global 3.4.4; make versionsTest MOREFLAGS=-I/usr/include/x86_64-linux-gnu && make clean
-    - run: make travis-install      && make clean
+    - run: make -C lib all           && make clean
+    - run: pyenv global 3.4.4; CPPFLAGS=-I/usr/include/x86_64-linux-gnu make versionsTest && make clean
+    - run: make test-install         && make clean
     - run: gcc -v; CFLAGS="-O2 -m32 -Werror" CPPFLAGS=-I/usr/include/x86_64-linux-gnu make check && make clean
     - run: clang -v; make staticAnalyze && make clean
-    - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static                  && make clean
-    - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static MOREFLAGS=-m64 && make clean
-    - run: make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static                  && make clean
-    - run: make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static              && make clean
+    - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static V=1       && make clean
+    - run: CFLAGS=-m64 LDFLAGS=-m64 make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static V=1 && make clean
+    - run: make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static V=1      && make clean
+    - run: make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static V=1  && make clean
     # Teardown
     #   If you break your build into multiple jobs with workflows, you will probably want to do the parts of this that are relevant in each
     # Save test results
diff --git a/.cirrus.yml b/.cirrus.yml
index e423538..d9936c8 100644
--- a/.cirrus.yml
+++ b/.cirrus.yml
@@ -1,5 +1,9 @@
-freebsd_instance:
-  image_family: freebsd-12-2
-
 task:
-  script: pkg install -y gmake && gmake test
+  name: FreeBSD
+  freebsd_instance:
+    matrix:
+      image_family: freebsd-14-0
+  install_script: pkg install -y gmake
+  script: |
+    cc -v
+    gmake test
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..bc22ba3
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,132 @@
+# This is the configuration file for clang-format, an automatic code formatter.
+# Introduction: https://clang.llvm.org/docs/ClangFormat.html
+# Supported options: https://clang.llvm.org/docs/ClangFormatStyleOptions.html
+
+Language: Cpp
+Standard: Latest
+
+ColumnLimit: 110
+
+UseTab: Never
+IndentWidth: 4
+PPIndentWidth: 2
+ContinuationIndentWidth: 4
+
+LineEnding: LF
+InsertNewlineAtEOF: true
+KeepEmptyLinesAtTheStartOfBlocks: false
+MaxEmptyLinesToKeep: 1
+
+IndentCaseBlocks: false
+IndentCaseLabels: false
+IndentGotoLabels: false
+IndentPPDirectives: AfterHash
+IndentWrappedFunctionNames: false
+
+AlignAfterOpenBracket: Align
+AlignArrayOfStructures: Right
+AlignEscapedNewlines: Left
+AlignOperands: Align
+AlignConsecutiveAssignments:
+    Enabled:          true
+    AcrossEmptyLines: false
+    AcrossComments:   false
+    AlignCompound:    false
+    PadOperators:     false
+AlignConsecutiveBitFields:
+    Enabled:          true
+    AcrossEmptyLines: false
+    AcrossComments:   false
+AlignConsecutiveDeclarations:
+    Enabled:          true
+    AcrossEmptyLines: false
+    AcrossComments:   false
+AlignConsecutiveMacros:
+    Enabled:          true
+    AcrossEmptyLines: false
+    AcrossComments:   false
+AlignTrailingComments:
+    Kind:           Leave
+    OverEmptyLines: 0
+
+BinPackArguments: true
+BinPackParameters: false
+AllowAllArgumentsOnNextLine: true
+AllowAllParametersOfDeclarationOnNextLine: false
+
+AllowShortBlocksOnASingleLine: Never
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortEnumsOnASingleLine: true
+AllowShortFunctionsOnASingleLine: None
+AllowShortIfStatementsOnASingleLine: AllIfsAndElse
+AllowShortLoopsOnASingleLine: false
+
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+BraceWrapping:
+    AfterCaseLabel:        false
+    AfterControlStatement: Never
+    AfterEnum:             false
+    AfterExternBlock:      false
+    AfterFunction:         true
+    AfterStruct:           false
+    AfterUnion:            false
+    BeforeElse:            false
+    BeforeWhile:           false
+    IndentBraces:          false
+    SplitEmptyFunction:    false
+    SplitEmptyRecord:      false
+BreakAfterAttributes: Never
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Custom
+BreakBeforeInlineASMColon: OnlyMultiline
+BreakBeforeTernaryOperators: true
+
+DerivePointerAlignment: false
+PointerAlignment: Left
+
+QualifierAlignment: Custom
+QualifierOrder: ["inline", "static", "volatile", "restrict", "const", "type"]
+
+ReflowComments: false
+BreakStringLiterals: false
+RemoveSemicolon: true
+RemoveParentheses: ReturnStatement
+InsertBraces: false
+SeparateDefinitionBlocks: Always
+
+SpaceAfterCStyleCast: false
+SpaceAfterLogicalNot: false
+SpaceAroundPointerQualifiers: Default
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeCaseColon: false
+SpaceBeforeParens: ControlStatements
+BitFieldColonSpacing: Both
+SpaceBeforeSquareBrackets: false
+SpaceInEmptyBlock: false
+SpacesBeforeTrailingComments: 1
+SpacesInSquareBrackets: false
+SpacesInLineCommentPrefix:
+    Minimum: 1
+    Maximum: -1
+
+SortIncludes: Never
+IncludeBlocks: Preserve
+IncludeIsMainRegex: ""
+IncludeCategories:
+    - {Regex: "<.*>",   Priority: -2, CaseSensitive: true}
+    - {Regex: "\".*\"", Priority: -1, CaseSensitive: true}
+
+AttributeMacros: ["__capability"]
+StatementAttributeLikeMacros: []
+StatementMacros: []
+
+PenaltyBreakAssignment: 200
+PenaltyBreakBeforeFirstCallParameter: 19
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakOpenParenthesis: 0
+PenaltyBreakString: 1000
+PenaltyExcessCharacter: 10
+PenaltyIndentedWhitespace: 0
+PenaltyReturnTypeOnItsOwnLine: 60
diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml
new file mode 100644
index 0000000..bc9a4d5
--- /dev/null
+++ b/.github/dependabot.yaml
@@ -0,0 +1,7 @@
+version: 2
+
+updates:
+  - package-ecosystem: github-actions
+    directory: /
+    schedule:
+      interval: weekly
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index 306d875..2c9071a 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -4,27 +4,19 @@
 
 ## USAN, ASAN (`lz4-ubsan-x64`, `lz4-ubsan-x86`, `lz4-asan-x64`)
 
-For now, `lz4-ubsan-*` ignores the exit code of `make usan` and `make usan32`.
-Because there are several issues which may take relatively long time to resolve.
+For now, `lz4-ubsan-*` uses the `-fsanitize-recover=pointer-overflow` flag:
+there are known cases of pointer overflow arithmetic within `lz4.c` fast compression.
+These cases are not dangerous with known architecture,
+but they are not guaranteed to work by the C standard,
+which means that, in some future, some new architecture or some new compiler
+may decide to do something funny that could break this behavior.
+Hence, in anticipation, it's better to remove them.
+This has been already achieved in `lz4hc.c`.
+However, the same attempt in `lz4.c` resulted in massive speed losses,
+which is not an acceptable cost for preemptively solving a "potential future" problem
+not active anywhere today.
+Therefore, a more acceptable work-around will have to be found first.
 
-We'll fully enable it when we ensure `make usan` is ready for all commits and PRs.
-
-See [#983](https://github.com/lz4/lz4/pull/983) for details.
-
-
-## C Compilers (`lz4-c-compilers`)
-
-- Our test doesn't use `gcc-4.5` due to installation issue of its package.  (`apt-get install gcc-4.5` fails on GH-Actions VM)
-
-- Currently, the following 32bit executable tests fail with all versions of `clang`.
-  - `CC=clang-X CFLAGS='-O3' make V=1 -C tests clean test-lz4c32`
-  - `CC=clang-X CFLAGS='-O3 -mx32' make V=1 -C tests clean test-lz4c32`
-  - See [#991](https://github.com/lz4/lz4/issues/991) for details.
-
-- Currently, the following 32bit executable tests fail with `gcc-11`
-  - `CC=gcc-11 CFLAGS='-O3' make V=1 -C tests clean test-lz4c32`
-  - `CC=gcc-11 CFLAGS='-O3 -mx32' make V=1 -C tests clean test-lz4c32`
-  - See [#991](https://github.com/lz4/lz4/issues/991) for details.
 
 
 ## cppcheck (`lz4-cppcheck`)
@@ -50,11 +42,7 @@
 
 # Difference with `.travis.yml`
 
-The following tests are not included yet.
-
-- name: Compile OSS-Fuzz targets
-
-The following tests will not be included due to limitation of GH-Actions.
+The following tests are not be included due to limitation of GH-Actions.
 
 - name: aarch64 real-hw tests
 - name: PPC64LE real-hw tests
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c490bc7..9efe8f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -16,6 +16,10 @@
 permissions:
   contents: read
 
+concurrency:
+  cancel-in-progress: true
+  group: ${{ github.workflow }}-${{ github.head_ref }}
+
 jobs:
   lz4-c-compilers:
     name: CC=${{ matrix.cc }}, ${{ matrix.os }}
@@ -27,7 +31,7 @@
           #
           #   pkgs         : apt-get package names.  It can include multiple package names which are delimited by space.
           #   cc           : C compiler executable.
-          #   cxx          : C++ compiler executable for `make ctocpptest`.
+          #   cxx          : C++ compiler executable for targets `cxxtest` and `ctocxxtest`.
           #   x32          : Set 'true' if compiler supports x32.  Otherwise, set 'false'.
           #                  Set 'fail' if it supports x32 but fails for now.  'fail' cases must be removed.
           #   x86          : Set 'true' if compiler supports x86 (-m32).  Otherwise, set 'false'.
@@ -38,44 +42,40 @@
           #   os           : GitHub Actions YAML workflow label.  See https://github.com/actions/virtual-environments#available-environments
 
           # cc
-          { pkgs: '',                                                   cc: cc,        cxx: c++,         x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-latest, },
+          { pkgs: '',                                                   cc: cc,        cxx: c++,         x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-latest, },
 
           # gcc
-          { pkgs: '',                                                   cc: gcc,       cxx: g++,         x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-latest, },
-          { pkgs: 'gcc-12 g++-12 lib32gcc-12-dev libx32gcc-12-dev',     cc: gcc-12,    cxx: g++-12,      x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
-          { pkgs: 'gcc-11 g++-11 lib32gcc-11-dev libx32gcc-11-dev',     cc: gcc-11,    cxx: g++-11,      x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
-          { pkgs: 'gcc-10 g++-10 lib32gcc-10-dev libx32gcc-10-dev',     cc: gcc-10,    cxx: g++-10,      x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
-          { pkgs: 'gcc-9 g++-9 lib32gcc-9-dev libx32gcc-9-dev',         cc: gcc-9,     cxx: g++-9,       x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
+          { pkgs: '',                                                   cc: gcc,       cxx: g++,         x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-latest, },
+        # { pkgs: 'gcc-13 g++-13 lib32gcc-13-dev libx32gcc-13-dev',     cc: gcc-13,    cxx: g++-13,      x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
+          { pkgs: 'gcc-12 g++-12 lib32gcc-12-dev libx32gcc-12-dev',     cc: gcc-12,    cxx: g++-12,      x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
+          { pkgs: 'gcc-11 g++-11 lib32gcc-11-dev libx32gcc-11-dev',     cc: gcc-11,    cxx: g++-11,      x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
+          { pkgs: 'gcc-10 g++-10 lib32gcc-10-dev libx32gcc-10-dev',     cc: gcc-10,    cxx: g++-10,      x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
+          { pkgs: 'gcc-9 g++-9 lib32gcc-9-dev libx32gcc-9-dev',         cc: gcc-9,     cxx: g++-9,       x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-22.04,  },
           { pkgs: 'gcc-8 g++-8 lib32gcc-8-dev libx32gcc-8-dev',         cc: gcc-8,     cxx: g++-8,       x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-20.04,  },
           { pkgs: 'gcc-7 g++-7 lib32gcc-7-dev libx32gcc-7-dev',         cc: gcc-7,     cxx: g++-7,       x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-20.04,  },
-          { pkgs: 'gcc-6 g++-6 lib32gcc-6-dev libx32gcc-6-dev',         cc: gcc-6,     cxx: g++-6,       x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-18.04,  },
-          { pkgs: 'gcc-5 g++-5 lib32gcc-5-dev libx32gcc-5-dev',         cc: gcc-5,     cxx: g++-5,       x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-18.04,  },
-          { pkgs: 'gcc-4.8 g++-4.8 lib32gcc-4.8-dev libx32gcc-4.8-dev', cc: gcc-4.8,   cxx: g++-4.8,     x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'true',  os: ubuntu-18.04,  },
 
           # clang
-          { pkgs: 'lib32gcc-11-dev libx32gcc-11-dev',                   cc: clang,     cxx: clang++,     x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-latest, },
-          { pkgs: 'clang-14  lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-14,  cxx: clang++-14,  x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
-          { pkgs: 'clang-13  lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-13,  cxx: clang++-13,  x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
-          { pkgs: 'clang-12  lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-12,  cxx: clang++-12,  x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
-          { pkgs: 'clang-11  lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-11,  cxx: clang++-11,  x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
-          { pkgs: 'clang-10  lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-10,  cxx: clang++-10,  x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
-          { pkgs: 'clang-9   lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-9,   cxx: clang++-9,   x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
-          { pkgs: 'clang-8   lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-8,   cxx: clang++-8,   x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
-          { pkgs: 'clang-7   lib32gcc-7-dev  libx32gcc-7-dev',          cc: clang-7,   cxx: clang++-7,   x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
-          { pkgs: 'clang-6.0 lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-6.0, cxx: clang++-6.0, x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
-          { pkgs: 'clang-5.0 lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-5.0, cxx: clang++-5.0, x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-18.04,  },
-          { pkgs: 'clang-4.0 lib32gcc-11-dev libx32gcc-11-dev',         cc: clang-4.0, cxx: clang++-4.0, x32: 'true', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-18.04,  },
-          { pkgs: 'clang-3.9',                                          cc: clang-3.9, cxx: clang++-3.9, x32: 'fail', x86: 'fail', cxxtest: 'false', freestanding: 'false', os: ubuntu-18.04,  },
+          { pkgs: 'lib32gcc-12-dev libx32gcc-12-dev',                   cc: clang,     cxx: clang++,     x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-latest, },
+          { pkgs: 'clang-15  lib32gcc-12-dev libx32gcc-12-dev',         cc: clang-15,  cxx: clang++-15,  x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
+          { pkgs: 'clang-14  lib32gcc-12-dev libx32gcc-12-dev',         cc: clang-14,  cxx: clang++-14,  x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
+          { pkgs: 'clang-13  lib32gcc-12-dev libx32gcc-12-dev',         cc: clang-13,  cxx: clang++-13,  x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
+          { pkgs: 'clang-12  lib32gcc-12-dev libx32gcc-12-dev',         cc: clang-12,  cxx: clang++-12,  x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
+          { pkgs: 'clang-11  lib32gcc-12-dev libx32gcc-12-dev',         cc: clang-11,  cxx: clang++-11,  x32: 'false', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-22.04,  },
+          { pkgs: 'clang-10  lib32gcc-10-dev libx32gcc-10-dev',         cc: clang-10,  cxx: clang++-10,  x32: 'fail', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
+          { pkgs: 'clang-9   lib32gcc-10-dev libx32gcc-10-dev',         cc: clang-9,   cxx: clang++-9,   x32: 'fail', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
+          { pkgs: 'clang-8   lib32gcc-10-dev libx32gcc-10-dev',         cc: clang-8,   cxx: clang++-8,   x32: 'fail', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
+          { pkgs: 'clang-7   lib32gcc-7-dev  libx32gcc-7-dev',          cc: clang-7,   cxx: clang++-7,   x32: 'fail', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
+          { pkgs: 'clang-6.0 lib32gcc-10-dev libx32gcc-10-dev',         cc: clang-6.0, cxx: clang++-6.0, x32: 'fail', x86: 'true', cxxtest: 'true',  freestanding: 'false', os: ubuntu-20.04,  },
         ]
 
     runs-on: ${{ matrix.os }}
     env:                        # Set environment variables
-      # We globally set CC and CXX to improve compatibility with .travis.yml
+      # We globally set CC and CXX to improve compatibility
       CC: ${{ matrix.cc }}
       CXX: ${{ matrix.cxx }}
       FIXME__LZ4_CI_IGNORE : ' echo Error.  But we ignore it for now.'
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
@@ -90,73 +90,61 @@
 
     - name: make
       if: always()
-      run: make V=1
+      run: make -j V=1
 
     - name: install test
       if: always()
-      run: make clean; make V=1 -C tests test-install
+      run: make -C tests test-install V=1
 
     - name: make all
       if: always()
-      run: make V=1 clean all
+      run: make clean; CFLAGS="-Werror -O0" make -j all V=1
 
     - name: make c_standards (C90)
       if: always()
-      run: make V=1 clean c_standards_c90
+      run: make clean; make -j c_standards_c90 V=1
 
     - name: make c_standards (C11)
       if: always()
-      run: make V=1 clean c_standards_c11
+      run: make clean; make -j c_standards_c11 V=1
 
-    - name: make c-to-c++
-      if: always()
-      run: make V=1 clean ctocpptest
-
-    - name: make cxxtest
+    - name: c lib for c++ program
       if: ${{ matrix.cxxtest == 'true' }}
-      run: make V=1 clean cxxtest
+      run: make clean; make -j ctocxxtest V=1
+
+    - name: compiled as c++ source
+      if: ${{ matrix.cxxtest == 'true' }}
+      run: make clean; make -j cxxtest V=1
 
     - name: make test-freestanding
       if: ${{ matrix.freestanding == 'true' }}
-      run: make V=1 clean test-freestanding
-
-    - name: make -C programs default
-      if: always()
-      run: make V=1 -C programs clean default
+      run: make clean; make test-freestanding V=1
 
     - name: make -C programs default -D_FORTIFY_SOURCE=2
       if: always()
-      run: CFLAGS='-fPIC' LDFLAGS='-pie -fPIE -D_FORTIFY_SOURCE=2' make V=1 -C programs clean default
+      run: make clean; CFLAGS='-fPIC' LDFLAGS='-pie -fPIE -D_FORTIFY_SOURCE=2' make -j -C programs default V=1
 
     - name: make -C tests test-lz4
       if: always()
-      run: make clean; MOREFLAGS='-Werror' make -j V=1 -C tests test-lz4
+      run: make clean; CPPFLAGS=-DLZ4IO_NO_TSAN_ONLY make -j V=1 -C tests test-lz4
 
-    - name: make clangtest (clang only)
-      if: ${{ startsWith( matrix.cc , 'clang' ) }}
-      run: make V=1 clean clangtest
-
-    - name: make -C tests test MOREFLAGS='-mx32'
+    - name: make -C tests test CFLAGS='-mx32'
       if: ${{ matrix.x32 == 'true' }}
-      run: make clean; LDFLAGS='-Wl,--verbose' MOREFLAGS='-mx32' make -j V=1 -C tests test
+      run: make clean; CFLAGS='-mx32' make -j -C tests test V=1
 
     - name: make -C tests test-lz4c32
       if: ${{ matrix.x86 == 'true' }}
-      run: LDFLAGS='-Wl,--verbose' MOREFLAGS='-Werror' make V=1 -C tests clean test-lz4c32
+      run: make clean; CFLAGS='-Werror -O1' make -j -C tests test-lz4c32 V=1
 
 
     ###############################################################
     #                                                             #
-    #      Remove this block when we stabilize the tests.         #
+    #      Remove this block when we relevant tests run properly  #
     #                                                             #
 
-    - name: make -C tests test MOREFLAGS='-mx32' || echo Ignore failure for now.
+    - name: make -C tests test CFLAGS='-mx32' || echo Ignore failure for now.
       if: ${{ matrix.x32 == 'fail' }}
-      run: make clean; LDFLAGS='-Wl,--verbose' MOREFLAGS='-mx32' make -j V=1 -C tests test || $FIXME__LZ4_CI_IGNORE
-
-    - name: make -C tests test-lz4c32 || echo Ignore failure for now.
-      if: ${{ matrix.x86 == 'fail' }}
-      run: make clean; LDFLAGS='-Wl,--verbose' MOREFLAGS='-Werror' make V=1 -C tests test-lz4c32 || $FIXME__LZ4_CI_IGNORE
+      run: make clean; CFLAGS='-mx32' make -C tests test V=1 || $FIXME__LZ4_CI_IGNORE
 
     #                                                             #
     ###############################################################
@@ -166,44 +154,44 @@
 ###############################################################
 # LZ4 self tests
 #
-# - Benchmark
+# - Fullbench
 # - Fuzzer
 # - LZ4 Frame
 # - LZ4 versions
 # - Custom LZ4_DISTANCE_MAX
 #
   lz4-benchmark:
-    name: Benchmark
+    name: Fullbench
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
         sudo apt-get update
         sudo apt-get install gcc-multilib
 
-    - name: benchmark (-C tests test-lz4)
-      run: make -j V=1 -C tests test-lz4
+    - name: test-lz4
+      run: make -j -C tests test-lz4 V=1
 
-    - name: benchmark (-C tests test-lz4c)
-      run: make -j V=1 -C tests test-lz4c
+    - name: test-lz4c
+      run: make -j -C tests test-lz4c V=1
 
-    - name: benchmark (-C tests test-lz4c32)
-      run: make V=1 -C tests test-lz4c32
+    - name: test-lz4c32
+      run: make -j -C tests test-lz4c32 V=1
 
-    - name: benchmark (-C tests test-fullbench)
-      run: make V=1 -C tests test-fullbench
+    - name: test-fullbench
+      run: make -j -C tests test-fullbench V=1
 
-    - name: benchmark (-C tests test-fullbench32)
-      run: make V=1 -C tests test-fullbench32
+    - name: test-fullbench32
+      run: make -j -C tests test-fullbench32 V=1
 
 
   lz4-fuzzer:
     name: Fuzzer test
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
@@ -214,57 +202,57 @@
       run: sudo sysctl -w vm.mmap_min_addr=4096
 
     - name: fuzzer
-      run: make V=1 -C tests test-fuzzer
+      run: make -j -C tests test-fuzzer V=1
 
     - name: fuzzer32
-      run: make V=1 -C tests test-fuzzer32
+      run: make -C tests test-fuzzer32 V=1
 
 
   lz4-standard-makefile-variables:
     name: LZ4 Makefile - support for standard variables
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: make standard_variables
-      run: make V=1 standard_variables
+      run: make standard_variables V=1
 
 
   lz4-versions:
     name: LZ4 versions test
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
         sudo apt-get update
         sudo apt-get install gcc-multilib
 
-    - name: make -C tests versionsTest
-      run: make V=1 -C tests versionsTest
+    - name: versionsTest
+      run: make -j -C tests versionsTest V=1
 
 
   lz4-abi:
-    name: LZ4 inter-versions ABI test
+    name: LZ4 inter-versions ABI compatibility test
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
         sudo apt-get update
         sudo apt-get install gcc-multilib
 
-    - name: make -C tests abiTests
-      run: make V=1 -C tests abiTests
+    - name: abiTests
+      run: make -j -C tests abiTests V=1
 
 
   lz4-frame:
     name: LZ4 frame test
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
@@ -272,16 +260,16 @@
         sudo apt-get install gcc-multilib
 
     - name: LZ4 frame test
-      run: make V=1 -C tests test-frametest
+      run: make -j -C tests test-frametest V=1
 
     - name: LZ4 frame test (32-bit)
-      run: make V=1 -C tests test-frametest32
+      run: make -j -C tests test-frametest32 V=1
 
   lz4-memory-usage:
     name: test different values of LZ4_MEMORY_USAGE
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: LZ4_MEMORY_USAGE
       run: make V=1 -C tests test-compile-with-lz4-memory-usage
 
@@ -290,23 +278,23 @@
     name: Custom LZ4_DISTANCE_MAX
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: custom LZ4_DISTANCE_MAX; test LZ4_USER_MEMORY_FUNCTIONS
       run: |
-        MOREFLAGS='-DLZ4_DISTANCE_MAX=8000' make V=1 check
-        make V=1 clean
-        make V=1 -C programs lz4-wlib
-        make V=1 clean
-        make V=1 -C tests fullbench-wmalloc  # test LZ4_USER_MEMORY_FUNCTIONS
-        make V=1 clean
-        CC="c++ -Wno-deprecated" make V=1 -C tests fullbench-wmalloc  # stricter function signature check
+        CPPFLAGS='-DLZ4_DISTANCE_MAX=8000' make V=1 check
+        make clean
+        make -C programs lz4-wlib V=1
+        make clean
+        make -C tests fullbench-wmalloc V=1  # test LZ4_USER_MEMORY_FUNCTIONS
+        make clean
+        CC="c++ -Wno-deprecated" make -C tests fullbench-wmalloc V=1 # stricter function signature check
 
   # test block device compression #1086
   lz4cli-block-device:
     name: Test lz4 compression on a block device
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: create a block device, compress it with lz4 # alternative : blindly use /dev/loop0, seems to always exist
       run: |
         make lz4
@@ -333,7 +321,7 @@
     name: make cppcheck
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: apt-get install
       run: |
         sudo apt-get update
@@ -352,7 +340,7 @@
     name: make staticAnalyze
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: apt-get install
       run: |
         sudo apt-get update
@@ -374,7 +362,7 @@
     name: valgrind
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: apt-get install
       run: |
         sudo apt-get update
@@ -392,27 +380,20 @@
   lz4-ubsan-x64:
     name: Linux x64 ubsan
     runs-on: ubuntu-latest
-    env:                        # Set environment variables
-      FIXME__LZ4_CI_IGNORE : ' echo Error.  But we ignore it for now.'
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: ubsan
-      #########################################################
-      # For now, we ignore the exit code of `make usan`.
-      # See "Known issues / lz4-ubsan-x64" in README.md
-      # When we'll resolve this issue, remove "|| $FIXME__LZ4_CI_IGNORE"
-      #########################################################
-      run: make V=1 clean usan MOREFLAGS='-Wcomma -Werror' || $FIXME__LZ4_CI_IGNORE
+      run: |
+        make clean
+        make V=1 usan
 
 
   lz4-ubsan-x86:
     name: Linux x86 ubsan
     runs-on: ubuntu-latest
-    env:                        # Set environment variables
-      FIXME__LZ4_CI_IGNORE : ' echo Error.  But we ignore it for now.'
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
@@ -421,36 +402,59 @@
         sudo apt-get install lib32gcc-11-dev
 
     - name: ubsan32
-      #########################################################
-      # For now, we ignore the exit code of `make usan32`.
-      # See "Known issues / lz4-ubsaan-x86" in README.md.
-      # When we'll resolve this issue, remove "|| $FIXME__LZ4_CI_IGNORE"
-      #########################################################
-      run: CC=clang make V=1 clean usan32 MOREFLAGS='-Wcomma -Werror' || $FIXME__LZ4_CI_IGNORE
+      run: |
+        make clean
+        CC=clang make V=1 usan32
 
 
   lz4-asan-x64:
     name: Linux x64 ASAN
     runs-on: ubuntu-latest
-    env:                        # Set environment variables
-      FIXME__LZ4_CI_IGNORE : ' echo Error.  But we ignore it for now.'
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: setup
       run: sudo sysctl -w vm.mmap_min_addr=4096
 
+    - name: check lz4
+      run: make clean; CFLAGS=-fsanitize=address LDFLAGS=-fsanitize=address make -j check V=1
+
     - name: frametest
-      run: CC=clang MOREFLAGS=-fsanitize=address make V=1 -C tests clean test-frametest
+      run: make clean; CFLAGS=-fsanitize=address LDFLAGS=-fsanitize=address make -j -C tests test-frametest V=1
 
     - name: fuzzer
-      run: CC=clang MOREFLAGS=-fsanitize=address make V=1 -C tests clean test-fuzzer
+      run: make clean; CFLAGS=-fsanitize=address LDFLAGS=-fsanitize=address make -j -C tests test-fuzzer V=1
+
+  lz4-msan-x64:
+    name: Linux x64 MSAN
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+
+    - name: check lz4
+      run: make clean; CC=clang CFLAGS=-fsanitize=memory LDFLAGS=-fsanitize=memory make -j check V=1
+
+    - name: frametest
+      run: make clean; CC=clang CFLAGS=-fsanitize=memory LDFLAGS=-fsanitize=memory make -j -C tests test-frametest V=1
+
+    - name: fuzzer
+      run: make clean; CC=clang CFLAGS=-fsanitize=memory LDFLAGS=-fsanitize=memory make -j -C tests test-fuzzer V=1
+
+  lz4-tsan-x64:
+    name: Linux x64 TSAN
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+
+    - name: lz4 cli
+      run: make clean; CC=clang CPPFLAGS="-fsanitize=thread" make -j -C tests test-lz4 V=1
+
 
   unicode-lint:
     name: lint unicode in ./lib/, ./tests/ and ./programs/
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: unicode lint
       run: bash ./tests/unicode_lint.sh
 
@@ -458,7 +462,7 @@
     name: make examples
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: apt-get install
       run: |
         sudo apt-get update
@@ -471,10 +475,7 @@
     - name: examples
       run: make V=1 clean examples
 
-    - name: examples (compile as C++ code)
-      run: make V=1 -C examples clean cxxtest
-
-  # lasts ~20mn
+  # lasts ~8mn
   oss-fuzz:
     runs-on: ubuntu-latest
     strategy:
@@ -493,11 +494,11 @@
       uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
       with:
         oss-fuzz-project-name: 'lz4'
-        fuzz-seconds: 600
+        fuzz-seconds: 300
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@v1
+      uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # https://github.com/actions/upload-artifact v4.3.4
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
@@ -510,20 +511,12 @@
 #
 # - QEMU (ARM, ARM64, PPC, PPC64LE, S390X)
 # - macOS
+# - Windows
 #
 
   # QEMU
   # All tests use QEMU (static) and gcc cross compiler.
   #
-  # note:
-  #   We don't employ completely matrix method which provides `MOREFLAGS`
-  #   etc in the matrix.  Because some platform may need its special
-  #   compiler options and test.
-  #   For example, xxHash already has tests for scalar and SIMD version of
-  #   it.  But compiler options are quite different between platforms.
-  #
-  #   So, please keep them simple and independent.
-  #
   lz4-qemu-platforms:
     name: QEMU ${{ matrix.type }}
     strategy:
@@ -537,19 +530,24 @@
           #   xemu : QEMU static emulator executable.
           #   os   : GitHub Actions YAML workflow label.  See https://github.com/actions/virtual-environments#available-environments
 
-          { type: ARM,      pkgs: 'qemu-system-arm   gcc-arm-linux-gnueabi',     xcc: arm-linux-gnueabi-gcc,     xemu: qemu-arm-static,     os: ubuntu-latest, },
-          { type: ARM64,    pkgs: 'qemu-system-arm   gcc-aarch64-linux-gnu',     xcc: aarch64-linux-gnu-gcc,     xemu: qemu-aarch64-static, os: ubuntu-latest, },
-          { type: PPC,      pkgs: 'qemu-system-ppc   gcc-powerpc-linux-gnu',     xcc: powerpc-linux-gnu-gcc,     xemu: qemu-ppc-static,     os: ubuntu-latest, },
-          { type: PPC64LE,  pkgs: 'qemu-system-ppc   gcc-powerpc64le-linux-gnu', xcc: powerpc64le-linux-gnu-gcc, xemu: qemu-ppc64le-static, os: ubuntu-latest, },
-          { type: S390X,    pkgs: 'qemu-system-s390x gcc-s390x-linux-gnu',       xcc: s390x-linux-gnu-gcc,       xemu: qemu-s390x-static,   os: ubuntu-latest, },
+          { type: ARM,      pkgs: 'qemu-system-arm   gcc-arm-linux-gnueabi',     xcc: arm-linux-gnueabi-gcc,     xemu: qemu-arm-static,     os: ubuntu-latest, makevar: "", },
+          { type: ARM64,    pkgs: 'qemu-system-arm   gcc-aarch64-linux-gnu',     xcc: aarch64-linux-gnu-gcc,     xemu: qemu-aarch64-static, os: ubuntu-latest, makevar: "", },
+          { type: PPC,      pkgs: 'qemu-system-ppc   gcc-powerpc-linux-gnu',     xcc: powerpc-linux-gnu-gcc,     xemu: qemu-ppc-static,     os: ubuntu-latest, makevar: "", },
+          { type: PPC64LE,  pkgs: 'qemu-system-ppc   gcc-powerpc64le-linux-gnu', xcc: powerpc64le-linux-gnu-gcc, xemu: qemu-ppc64le-static, os: ubuntu-latest, makevar: "", },
+          { type: S390X,    pkgs: 'qemu-system-s390x gcc-s390x-linux-gnu',       xcc: s390x-linux-gnu-gcc,       xemu: qemu-s390x-static,   os: ubuntu-latest, makevar: "", },
+          { type: MIPS,     pkgs: 'qemu-system-mips gcc-mips-linux-gnu',         xcc: mips-linux-gnu-gcc,        xemu: qemu-mips-static,    os: ubuntu-latest, makevar: "", },
+          { type: M68K,     pkgs: 'qemu-system-m68k gcc-m68k-linux-gnu',         xcc: m68k-linux-gnu-gcc,        xemu: qemu-m68k-static,    os: ubuntu-latest, makevar: "HAVE_MULTITHREAD=0", }, # bug in MT mode on m68k
+          { type: RISC-V,   pkgs: 'qemu-system-riscv64 gcc-riscv64-linux-gnu',   xcc: riscv64-linux-gnu-gcc,     xemu: qemu-riscv64-static, os: ubuntu-latest, makevar: "", },
+          { type: SPARC,    pkgs: 'qemu-system-sparc gcc-sparc64-linux-gnu',     xcc: sparc64-linux-gnu-gcc,     xemu: qemu-sparc64-static, os: ubuntu-20.04, makevar: "", },
         ]
 
     runs-on: ${{ matrix.os }}
     env:                        # Set environment variables
       XCC: ${{ matrix.xcc }}
       XEMU: ${{ matrix.xemu }}
+      MAKEVAR: ${{ matrix.makevar }}
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: apt-get install
       run: |
@@ -564,25 +562,18 @@
         echo && $XCC -v                       # Show built-in specs
         echo && type $XEMU && which $XEMU && $XEMU --version
 
-    - name: ARM64
-      if: ${{ matrix.type == 'ARM64' }}
-      run: make V=1 platformTest CC=$XCC QEMU_SYS=$XEMU
-
-    - name: ARM
-      if: ${{ matrix.type == 'ARM' }}
-      run: make V=1 platformTest CC=$XCC QEMU_SYS=$XEMU
-
-    - name: PPC
-      if: ${{ matrix.type == 'PPC' }}
-      run: make V=1 platformTest CC=$XCC QEMU_SYS=$XEMU
+    - name: ARM-ARM64-PPC-S390X
+      if: ${{ matrix.type == 'ARM' || matrix.type == 'ARM64' || matrix.type == 'PPC' || matrix.type == 'S390X'}}
+      run: make platformTest V=1  CC=$XCC QEMU_SYS=$XEMU
 
     - name: PPC64LE
       if: ${{ matrix.type == 'PPC64LE' }}
-      run: make V=1 platformTest CC=$XCC QEMU_SYS=$XEMU MOREFLAGS=-m64
+      run: CFLAGS=-m64 make platformTest V=1 CC=$XCC QEMU_SYS=$XEMU
 
-    - name: S390X
-      if: ${{ matrix.type == 'S390X' }}
-      run: make V=1 platformTest CC=$XCC QEMU_SYS=$XEMU
+    - name: MIPS-M68K-RISCV-SPARC
+      if: ${{ matrix.type == 'MIPS' || matrix.type == 'M68K' || matrix.type == 'RISC-V' || matrix.type == 'SPARC' }}
+      run: make platformTest V=1 CC=$XCC QEMU_SYS=$XEMU $MAKEVAR
+
 
 
   # macOS
@@ -590,7 +581,7 @@
     name: macOS
     runs-on: macos-latest
     steps:
-    - uses: actions/checkout@v2
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: Environment info
       run: |
@@ -599,10 +590,10 @@
         echo && sysctl -a | grep machdep.cpu   # cpuinfo
 
     - name: make default
-      run: CFLAGS="-Werror" make V=1 clean default
+      run: make clean; CFLAGS="-Werror -O0" make default V=1
 
     - name: make test
-      run: make clean; make -j V=1 test MOREFLAGS='-Werror -Wconversion -Wno-sign-conversion'
+      run: make clean; CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" make -j test V=1
 
     - name: Ensure `make test` doesn't depend on the status of the console
       # see issue #990 for detailed explanations
@@ -610,50 +601,19 @@
 
 
 ###############################################################
-# Build systems
+# Build systems (other than make)
 #
-# - make
 # - cmake
+# - visual
 # - meson
 #
 
-  # make
-  lz4-build-make:
-    name: make
-    runs-on: ubuntu-latest
-    steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
-
-    - name: Environment info
-      run: |
-        echo && type cc && which cc && cc --version
-        echo && type make && which make && make -v
-
-    - name: make
-      run: make V=1
-
-
-  lz4-build-make-travis-install:
-    name: make travis-install
-    runs-on: ubuntu-latest
-    steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
-
-    - name: travis-install
-      run: make V=1 clean travis-install
-
-    - name: travis-install result
-      run: |
-        echo && echo Installed files
-        ( cd ~/install_test_dir; find .; )
-
-
   # cmake
   lz4-build-cmake:
     name: cmake
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: Environment info
       run: |
@@ -662,31 +622,94 @@
 
     - name: cmake
       run: |
-        cd build/cmake
-        mkdir build
-        cd build
-        cmake ..
-        CFLAGS=-Werror make VERBOSE=1
+        CFLAGS="-Werror -O1" cmake -S build/cmake -B build -D CMAKE_INSTALL_PREFIX=install
+        VERBOSE=1 cmake --build build --target install
+        cmake -S tests/cmake -B build_test -D CMAKE_INSTALL_PREFIX=install
+        VERBOSE=1 cmake --build build_test
 
+  lz4-build-cmake-static-lib: # See https://github.com/lz4/lz4/issues/1269
+    name: cmake (static lib)
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+
+    - name: Environment info
+      run: |
+        echo && type cmake && which cmake && cmake --version
+        echo && type make && which make && make -v
+
+    - name: cmake (static lib)
+      run: |
+        CFLAGS="-Werror -O1" cmake -S build/cmake -B build -D CMAKE_INSTALL_PREFIX=install_test_dir -DBUILD_STATIC_LIBS=ON
+        VERBOSE=1 cmake --build build --target install
+        cmake -S tests/cmake -B build_test -D CMAKE_INSTALL_PREFIX=install_test_dir
+        VERBOSE=1 cmake --build build_test
 
   # Invoke cmake via Makefile
   lz4-build-make-cmake:
-    name: make cmake
+    name: make cmakebuild
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
-    - name: make cmake
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+    - name: make cmakebuild
       # V=1 for lz4 Makefile, VERBOSE=1 for cmake Makefile.
-      run: make V=1 VERBOSE=1 clean cmake
+      run: make clean; make cmakebuild V=1 VERBOSE=1
 
+  # Windows + Visual
+  lz4-platform-windows:
+    name: ${{ matrix.system.os }}
+    runs-on: ${{ matrix.system.os }}
+    strategy:
+      fail-fast: false  # 'false' means Don't stop matrix workflows even if some matrix failed.
+      matrix:
+        system: [
+          { os: windows-2022, build_path: ".\\build\\VS2022" },
+        ]
+    steps:
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+
+    - name: Build ${{ matrix.system.os }}, Win32
+      run: |
+        pushd ${{ matrix.system.build_path }}
+        .\\build-and-test-win32-release.bat
+        popd
+
+    - name: Build ${{ matrix.system.os }}, x64
+      run: |
+        pushd ${{ matrix.system.build_path }}
+        .\\build-and-test-x64-release.bat
+        popd
+
+    - name: VS solution generation
+      run: |
+        pushd ".\\build\\visual"
+        .\\generate_vs2022.cmd
+        popd
+
+    - name: Upload Generated VS2022 Directory
+      uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # https://github.com/actions/upload-artifact v4.3.4
+      with:
+        name: VS2022-Build-Dir
+        path: "build/visual/Visual Studio 17 2022"
+
+    - name: Build executable with generated solution
+      run: |
+        cmake --build "build/visual/Visual Studio 17 2022" --config Debug
+
+    - name: Minimal runtime test
+      run: |
+        & ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe" -vvV
+        & ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe" -bi1
+        & ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe" ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe"
+        & ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe" -t ".\\build\\visual\\Visual Studio 17 2022\\Debug\\lz4.exe.lz4"
 
   # Meson
   lz4-build-meson:
     name: Meson + Ninja
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2 # https://github.com/actions/checkout
-    - uses: actions/setup-python@v2 # https://github.com/actions/setup-python
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
+    - uses: actions/setup-python@39cd14951b08e74b54015e9e001cdefcf80e669f # https://github.com/actions/setup-python v5.1.1
       with:
         python-version: '3.x'
 
@@ -703,10 +726,11 @@
         echo && type python && which python && python --version
         echo && type meson && which meson && meson --version
 
-    - name: meson
+    - name: setup
       # 'run: >' replaces all newlines in the following block with spaces
       run: >
         meson setup
+        --fatal-meson-warnings
         --buildtype=debug
         -Db_lundef=false
         -Dauto_features=enabled
@@ -714,11 +738,15 @@
         -Dcontrib=true
         -Dtests=true
         -Dexamples=true
-        contrib/meson build
+        build/meson builddir
+
+    - name: test
+      run: |
+        meson test -C builddir
 
     - name: staging
       run: |
-        cd build
+        cd builddir
         DESTDIR=./staging ninja install
         tree ./staging
 
@@ -731,7 +759,7 @@
     name: git version tag checking for release
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@v2
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
     - name: make -C tests checkTag
       if: startsWith(github.ref, 'refs/tags/v')   # If git tag name starts with 'v'
       run: |
@@ -749,15 +777,15 @@
     strategy:
       matrix:
         include: [
-          { os: ubuntu-latest,  }, # https://github.com/actions/virtual-environments/
-          { os: ubuntu-22.04,   }, # https://github.com/actions/virtual-environments/blob/main/images/linux/Ubuntu2204-Readme.md
-          { os: ubuntu-20.04,   }, # https://github.com/actions/virtual-environments/blob/main/images/linux/Ubuntu2004-Readme.md
-          { os: ubuntu-18.04,   }, # https://github.com/actions/virtual-environments/blob/main/images/linux/Ubuntu1804-Readme.md
+          { os: ubuntu-latest,  }, # https://github.com/actions/runner-images/?tab=readme-ov-file#available-images
+          { os: ubuntu-24.04,   }, # https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2404-Readme.md
+          { os: ubuntu-22.04,   }, # https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md
+          { os: ubuntu-20.04,   }, # https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2004-Readme.md
         ]
 
     runs-on: ${{ matrix.os }}
     steps:
-    - uses: actions/checkout@v2
+    - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # https://github.com/actions/checkout v4.1.7
 
     - name: init
       run: |
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
new file mode 100644
index 0000000..20aad7e
--- /dev/null
+++ b/.github/workflows/scorecard.yml
@@ -0,0 +1,65 @@
+# This workflow uses actions that are not certified by GitHub. They are provided
+# by a third-party and are governed by separate terms of service, privacy
+# policy, and support documentation.
+
+name: Scorecard supply-chain security
+on:
+  # For Branch-Protection check. Only the default branch is supported. See
+  # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
+  branch_protection_rule:
+  # To guarantee Maintained check is occasionally updated. See
+  # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
+  schedule:
+    - cron: '23 22 * * 3'
+  push:
+    branches: [ "dev" ]
+
+# Declare default permissions as read only.
+permissions: read-all
+
+jobs:
+  analysis:
+    name: Scorecard analysis
+    runs-on: ubuntu-latest
+    permissions:
+      # Needed to upload the results to code-scanning dashboard.
+      security-events: write
+      # Needed to publish results and get a badge (see publish_results below).
+      id-token: write
+
+    steps:
+      - name: "Checkout code"
+        uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
+        with:
+          persist-credentials: false
+
+      - name: "Run analysis"
+        uses: ossf/scorecard-action@dc50aa9510b46c811795eb24b2f1ba02a914e534 # v2.3.3
+        with:
+          results_file: results.sarif
+          results_format: sarif
+          # (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
+          # you want to enable the Branch-Protection check on a *public* repository
+          # To create the PAT, follow the steps in
+          # https://github.com/ossf/scorecard-action#authentication-with-fine-grained-pat-optional
+          # repo_token: ${{ secrets.SCORECARD_TOKEN }}
+
+          # - Publish results to OpenSSF REST API for easy access by consumers
+          # - Allows the repository to include the Scorecard badge.
+          # - See https://github.com/ossf/scorecard-action#publishing-results.
+          publish_results: true
+
+      # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
+      # format to the repository Actions tab.
+      - name: "Upload artifact"
+        uses: actions/upload-artifact@0b2256b8c012f0828dc542b3febcab082c67f72b # v4.3.4
+        with:
+          name: SARIF file
+          path: results.sarif
+          retention-days: 5
+
+      # Upload the results to GitHub's code scanning dashboard.
+      - name: "Upload to code-scanning"
+        uses: github/codeql-action/upload-sarif@4fa2a7953630fd2f3fb380f21be14ede0169dd4f # v3.25.12
+        with:
+          sarif_file: results.sarif
diff --git a/.gitignore b/.gitignore
index ed02057..cacde29 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,11 +21,16 @@
 
 # IDE / editors files
 .clang_complete
+.vscode
 _codelite/
 _codelite_lz4/
 bin/
 *.zip
 *.swp
+compile_flags.txt
+compile_commands.json
+.vscode
+.cache
 
 # analyzers
 infer-out
@@ -41,3 +46,7 @@
 # test artifacts
 *.lz4
 tmp*
+
+# generated Windows resource files
+lib/*.rc
+programs/*.rc
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 0aeea6e..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-language: c
-
-matrix:
-  fast_finish: true
-  include:
-
-    - name: aarch64 real-hw tests
-      arch: arm64
-      script:
-        - make test
-
-    - name: PPC64LE real-hw tests
-      arch: ppc64le
-      script:
-        - make test
-
-    - name: IBM s390x real-hw tests
-      arch: s390x
-      script:
-        - make test
-
-    # tag-specific test
-    - name: tag build
-      if: tag =~ ^v[0-9]\.[0-9]
-      os: linux
-      script:
-        - make -C tests checkTag
-        - tests/checkTag "$TRAVIS_BRANCH"
-
-    # oss-fuzz compilation test
-    - name: Compile OSS-Fuzz targets
-      script:
-        - ./ossfuzz/travisoss.sh
-
-    # Unicode lint
-    # See https://github.com/lz4/lz4/issues/1018
-    - name: Run Unicode lint
-      script:
-        - ./tests/unicode_lint.sh
-
-  allow_failures:
-    - env: ALLOW_FAILURES=true
diff --git a/CODING_STYLE b/CODING_STYLE
new file mode 100644
index 0000000..0e94f1e
--- /dev/null
+++ b/CODING_STYLE
@@ -0,0 +1,57 @@
+LZ4 CODING STYLE
+================
+
+When contributing code and patches to the `LZ4` project, the following rules are expected to be followed for a successful merge.
+
+
+Library
+-------
+
+The library's source code in `lib/` directory has a BSD 2-clause license.
+It's designed to be integrated into 3rd party applications.
+
+It adheres relatively strictly to vanilla `C90`, with the following exceptions:
+- `long long` type is required, in order to support 64-bit values
+- Variadic Macros are used for debug mode (but not required in release mode)
+
+Beyond that, all other rules and limitations of C90 must be respected, including `/* ... */` comment style only, and variable declaration at top of block only. The automated CI test suite will check for these rules.
+
+The code is allowed to use more modern variants (C99 / C11 / C23) when useful
+as long as it provides a clean C90 backup for older compilers.
+For example, C99+ compilers will employ the `restrict` keyword, while `C90` ones will ignore it, thanks to conditional macros.
+This ensures maximum portability across a wide range of systems.
+
+Moreover, in the interest of safety, the code has to respect a fairly strigent list of additional restrictions, provided through warning flags, the list of which is maintained within `Makefile`.
+Among the less common ones, we want the source to be compatible with `-Wc++-compat`, which ensures that the code can be compiled "as is", with no modification, as C++ code. It makes it possible to copy-paste the code into other C++ source files, or the source files are just dropped into a C++ environment which then compiles them as C++ source files.
+
+
+Command Line Interface
+----------------------
+
+The CLI executable's source code in `programs/` directory has a GPLv2+ license.
+While it's designed to be portable and freely distributable, it's not meant to be integrated into 3rd party applications.
+The license difference is meant to reflect that choice.
+
+Similar to the library, the CLI adheres relatively strictly to vanilla `C90`, and features the same exceptions:
+- `long long` requirement for 64-bit values
+- Variadic Macros for console messages (now used all the time, not just debug mode)
+
+The code can also use system-specific libraries and symbols (such as `posix` ones)
+as long as it provides a backup for plain `C90` platforms.
+It's even allowed to lose capabilities, as long as the CLI can be cleanly compiled on `C90`.
+For example, systems without `<pthread>` support nor Completion Ports will just not feature multi-threading support, and run single threaded.
+
+In the interest of build familiarity, the CLI source code also respects the same set of advanced warning flags as the library.
+That being said, this last part is debatable and could deviate in the future.
+For example, there are less reasons to support `-Wc++-compat` on the CLI side, since it's not meant to be integrated into 3rd party applications.
+
+
+Others
+------
+
+The repository includes other directories with their own set of compilable projects, such as `tests/`, `examples/` and `contrib/`.
+
+These repositories do not have to respect the same set of restrictions, and can employ a larger array of different languages.
+For example, some tests employ `sh`, and others employ `python`.
+
+These directories may nonetheless include several targets employing the same coding convention as the `lz4` library. This is in a no way a rule, more like a side effect of build familiarity.
diff --git a/LICENSE b/LICENSE
index 1b84cc3..ba8a290 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
 This repository uses 2 different licenses :
 - all files in the `lib` directory use a BSD 2-Clause license
-- all other files use a GPLv2 license, unless explicitly stated otherwise
+- all other files use a GPL-2.0-or-later license, unless explicitly stated otherwise
 
 Relevant license is reminded at the top of each source file,
 and with presence of COPYING or LICENSE file in associated directories.
diff --git a/METADATA b/METADATA
index 4212a78..3fdd33f 100644
--- a/METADATA
+++ b/METADATA
@@ -1,15 +1,19 @@
+# This project was upgraded with external_updater.
+# Usage: tools/external_updater/updater.sh update external/lz4
+# For more info, check https://cs.android.com/android/platform/superproject/main/+/main:tools/external_updater/README.md
+
 name: "lz4"
 description: "Extremely Fast Compression algorithm http://www.lz4.org"
 third_party {
-  url {
-    type: GIT
-    value: "https://github.com/lz4/lz4.git"
-  }
-  version: "v1.9.4"
   license_type: RESTRICTED
   last_upgrade_date {
-    year: 2022
+    year: 2024
     month: 10
-    day: 6
+    day: 1
+  }
+  identifier {
+    type: "Git"
+    value: "https://github.com/lz4/lz4.git"
+    version: "v1.10.0"
   }
 }
diff --git a/Makefile b/Makefile
index e70c3db..dbf4910 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
 # ################################################################
 # LZ4 - Makefile
-# Copyright (C) Yann Collet 2011-2020
+# Copyright (C) Yann Collet 2011-2023
 # All rights reserved.
 #
 # BSD license
@@ -61,7 +61,8 @@
 lz4-release : lib-release
 lz4 lz4-release :
 	$(MAKE) -C $(PRGDIR) $@
-	cp $(PRGDIR)/lz4$(EXT) .
+	$(LN_SF) $(PRGDIR)/lz4$(EXT) .
+	echo lz4 build completed
 
 .PHONY: examples
 examples: liblz4.a
@@ -84,7 +85,7 @@
 	$(MAKE) -C $(FUZZDIR) $@ > $(VOID)
 	$(MAKE) -C contrib/gen_manual $@ > $(VOID)
 	$(RM) lz4$(EXT)
-	$(RM) -r $(CMAKE_BUILD_DIR)
+	$(RM) -r $(CMAKE_BUILD_DIR) $(MESON_BUILD_DIR)
 	@echo Cleaning completed
 
 
@@ -99,8 +100,8 @@
 	$(MAKE) -C $(LZ4DIR) $@
 	$(MAKE) -C $(PRGDIR) $@
 
-.PHONY: travis-install
-travis-install:
+.PHONY: test-install
+test-install:
 	$(MAKE) -j1 install DESTDIR=~/install_test_dir
 
 endif   # POSIX_ENV
@@ -113,11 +114,18 @@
 CMAKE_PARAMS = -G"MSYS Makefiles"
 endif
 
-.PHONY: cmake
-cmake:
+.PHONY: cmakebuild
+cmakebuild:
 	mkdir -p $(CMAKE_BUILD_DIR)
 	cd $(CMAKE_BUILD_DIR); $(CMAKE) $(CMAKE_PARAMS) ..; $(CMAKE) --build .
 
+MESON ?= meson
+MESON_BUILD_DIR ?= mesonBuildDir
+
+.PHONY: mesonbuild
+mesonbuild:
+	$(MESON) setup --fatal-meson-warnings --buildtype=debug -Db_lundef=false -Dauto_features=enabled -Dprograms=true -Dcontrib=true -Dtests=true -Dexamples=true build/meson $(MESON_BUILD_DIR)
+	$(MESON) test -C $(MESON_BUILD_DIR)
 
 #------------------------------------------------------------------------
 # make tests validated only for MSYS and Posix environments
@@ -137,23 +145,6 @@
 	$(MAKE) -C $(TESTDIR) $@
 	$(MAKE) -C $(EXDIR) $@
 
-.PHONY: clangtest
-clangtest: CFLAGS += -Werror -Wconversion -Wno-sign-conversion
-clangtest: CC = clang
-clangtest: clean
-	$(CC) -v
-	$(MAKE) -C $(LZ4DIR)  all CC=$(CC)
-	$(MAKE) -C $(PRGDIR)  all CC=$(CC)
-	$(MAKE) -C $(TESTDIR) all CC=$(CC)
-
-.PHONY: clangtest-native
-clangtest-native: CFLAGS = -O3 -Werror -Wconversion -Wno-sign-conversion
-clangtest-native: clean
-	clang -v
-	$(MAKE) -C $(LZ4DIR)  all    CC=clang
-	$(MAKE) -C $(PRGDIR)  native CC=clang
-	$(MAKE) -C $(TESTDIR) native CC=clang
-
 .PHONY: usan
 usan: CC      = clang
 usan: CFLAGS  = -O3 -g -fsanitize=undefined -fno-sanitize-recover=undefined -fsanitize-recover=pointer-overflow
@@ -162,10 +153,10 @@
 	CC=$(CC) CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS)' $(MAKE) test FUZZER_TIME="-T30s" NB_LOOPS=-i1
 
 .PHONY: usan32
-usan32: CFLAGS = -m32 -O3 -g -fsanitize=undefined
+usan32: CFLAGS = -m32 -O3 -g -fsanitize=undefined -fno-sanitize-recover=undefined -fsanitize-recover=pointer-overflow
 usan32: LDFLAGS = $(CFLAGS)
 usan32: clean
-	$(MAKE) test FUZZER_TIME="-T30s" NB_LOOPS=-i1
+	CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS)' $(MAKE) V=1 test FUZZER_TIME="-T30s" NB_LOOPS=-i1
 
 SCANBUILD ?= scan-build
 SCANBUILD_FLAGS += --status-bugs -v --force-analyze-debug-code
@@ -181,24 +172,36 @@
 platformTest: clean
 	@echo "\n ---- test lz4 with $(CC) compiler ----"
 	$(CC) -v
-	CFLAGS="-O3 -Werror"         $(MAKE) -C $(LZ4DIR) all
-	CFLAGS="-O3 -Werror -static" $(MAKE) -C $(PRGDIR) all
-	CFLAGS="-O3 -Werror -static" $(MAKE) -C $(TESTDIR) all
+	CFLAGS="$(CFLAGS) -O3 -Werror"         $(MAKE) -C $(LZ4DIR) all
+	CFLAGS="$(CFLAGS) -O3 -Werror -static" $(MAKE) -C $(PRGDIR) all
+	CFLAGS="$(CFLAGS) -O3 -Werror -static" $(MAKE) -C $(TESTDIR) all
 	$(MAKE) -C $(TESTDIR) test-platform
 
 .PHONY: versionsTest
-versionsTest: clean
+versionsTest:
+	$(MAKE) -C $(TESTDIR) clean
 	$(MAKE) -C $(TESTDIR) $@
 
 .PHONY: test-freestanding
 test-freestanding:
-	$(MAKE) -C $(TESTDIR) clean $@
+	$(MAKE) -C $(TESTDIR) clean
+	$(MAKE) -C $(TESTDIR) $@
+
+# test linking C libraries from C++ executables
+.PHONY: ctocxxtest
+ctocxxtest: LIBCC="$(CC)"
+ctocxxtest: EXECC="$(CXX) -Wno-deprecated"
+ctocxxtest: CFLAGS=-O0
+ctocxxtest:
+	CC=$(LIBCC) $(MAKE) -C $(LZ4DIR)  CFLAGS="$(CFLAGS)" all
+	CC=$(LIBCC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" lz4.o lz4hc.o lz4frame.o
+	CC=$(EXECC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" all
 
 .PHONY: cxxtest cxx32test
+cxx32test: CFLAGS += -m32
 cxxtest cxx32test: CC := "$(CXX) -Wno-deprecated"
 cxxtest cxx32test: CFLAGS = -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror
-cxx32test: CFLAGS += -m32
-cxxtest cxx32test: clean
+cxxtest cxx32test:
 	$(CXX) -v
 	CC=$(CC) $(MAKE) -C $(LZ4DIR)  all CFLAGS="$(CFLAGS)"
 	CC=$(CC) $(MAKE) -C $(PRGDIR)  all CFLAGS="$(CFLAGS)"
@@ -206,34 +209,25 @@
 
 .PHONY: cxx17build
 cxx17build : CC = "$(CXX) -Wno-deprecated"
-cxx17build : CFLAGS = -std=c++17 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror -pedantic
+cxx17build : CFLAGS = -std=c++17 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror -Wpedantic
 cxx17build : clean
 	$(CXX) -v
 	CC=$(CC) $(MAKE) -C $(LZ4DIR)  all CFLAGS="$(CFLAGS)"
 	CC=$(CC) $(MAKE) -C $(PRGDIR)  all CFLAGS="$(CFLAGS)"
 	CC=$(CC) $(MAKE) -C $(TESTDIR) all CFLAGS="$(CFLAGS)"
 
-.PHONY: ctocpptest
-ctocpptest: LIBCC="$(CC)"
-ctocpptest: TESTCC="$(CXX)"
-ctocpptest: CFLAGS=
-ctocpptest: clean
-	CC=$(LIBCC)  $(MAKE) -C $(LZ4DIR)  CFLAGS="$(CFLAGS)" all
-	CC=$(LIBCC)  $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" lz4.o lz4hc.o lz4frame.o
-	CC=$(TESTCC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" all
-
 .PHONY: c_standards
 c_standards: clean c_standards_c11 c_standards_c99 c_standards_c90
 
 .PHONY: c_standards_c90
 c_standards_c90: clean
-	$(MAKE) clean; CFLAGS="-std=c90   -Werror -pedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost
-	$(MAKE) clean; CFLAGS="-std=gnu90 -Werror -pedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost
+	$(MAKE) clean; CFLAGS="-std=c90   -Werror -Wpedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost
+	$(MAKE) clean; CFLAGS="-std=gnu90 -Werror -Wpedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost
 
 .PHONY: c_standards_c99
 c_standards_c99: clean
-	$(MAKE) clean; CFLAGS="-std=c99   -Werror -pedantic" $(MAKE) all
-	$(MAKE) clean; CFLAGS="-std=gnu99 -Werror -pedantic" $(MAKE) all
+	$(MAKE) clean; CFLAGS="-std=c99   -Werror -Wpedantic" $(MAKE) all
+	$(MAKE) clean; CFLAGS="-std=gnu99 -Werror -Wpedantic" $(MAKE) all
 
 .PHONY: c_standards_c11
 c_standards_c11: clean
@@ -243,7 +237,8 @@
 # are correctly transmitted at compilation stage.
 # This test is meant to detect issues like https://github.com/lz4/lz4/issues/958
 .PHONY: standard_variables
-standard_variables: clean
+standard_variables:
+	$(MAKE) clean
 	@echo =================
 	@echo Check support of Makefile Standard variables through environment
 	@echo note : this test requires V=1 to work properly
@@ -259,13 +254,13 @@
 	# supported in some part of the Makefile, and missed in others.
 	# So the test checks if they are present the _right nb of times_.
 	# However, checking static quantities makes this test brittle,
-	# because quantities (7, 2 and 1) can still evolve in future,
+	# because quantities (10, 2 and 1) can still evolve in future,
 	# for example when source directories or Makefile evolve.
-	if [ $$(grep CC_TEST tmpsv | wc -l) -ne 7 ]; then \
+	if [ $$(grep CC_TEST tmpsv | wc -l) -ne 10 ]; then \
 		echo "CC environment variable missed" && False; fi
-	if [ $$(grep CFLAGS_TEST tmpsv | wc -l) -ne 7 ]; then \
+	if [ $$(grep CFLAGS_TEST tmpsv | wc -l) -ne 10 ]; then \
 		echo "CFLAGS environment variable missed" && False; fi
-	if [ $$(grep CPPFLAGS_TEST tmpsv | wc -l) -ne 7 ]; then \
+	if [ $$(grep CPPFLAGS_TEST tmpsv | wc -l) -ne 10 ]; then \
 		echo "CPPFLAGS environment variable missed" && False; fi
 	if [ $$(grep LDFLAGS_TEST tmpsv | wc -l) -ne 2 ]; then \
 		echo "LDFLAGS environment variable missed" && False; fi
diff --git a/Makefile.inc b/Makefile.inc
index e78298c..0ccc2da 100644
--- a/Makefile.inc
+++ b/Makefile.inc
@@ -38,26 +38,26 @@
 endif
 
 ifneq (,$(filter Windows%,$(TARGET_OS)))
-LIBLZ4 = liblz4-$(LIBVER_MAJOR)
-LIBLZ4_EXP = liblz4.lib
-WINBASED   = yes
+LIBLZ4_NAME = liblz4-$(LIBVER_MAJOR)
+LIBLZ4_EXP  = liblz4.lib
+WINBASED    = yes
 else
-LIBLZ4_EXP = liblz4.dll.a
+LIBLZ4_EXP  = liblz4.dll.a
   ifneq (,$(filter MINGW%,$(TARGET_OS)))
-LIBLZ4     = liblz4
-WINBASED   = yes
+LIBLZ4_NAME = liblz4
+WINBASED    = yes
   else
     ifneq (,$(filter MSYS%,$(TARGET_OS)))
-LIBLZ4     = msys-lz4-$(LIBVER_MAJOR)
-WINBASED   = yes
+LIBLZ4_NAME = msys-lz4-$(LIBVER_MAJOR)
+WINBASED    = yes
     else
       ifneq (,$(filter CYGWIN%,$(TARGET_OS)))
-LIBLZ4     = cyglz4-$(LIBVER_MAJOR)
-WINBASED   = yes
+LIBLZ4_NAME = cyglz4-$(LIBVER_MAJOR)
+WINBASED    = yes
       else
-LIBLZ4     = liblz4.$(SHARED_EXT_VER)
-WINBASED   = no
-EXT        =
+LIBLZ4_NAME = liblz4
+WINBASED    = no
+EXT         =
       endif
     endif
   endif
@@ -65,9 +65,11 @@
 
 ifeq ($(WINBASED),yes)
 EXT        = .exe
-WINDRES    = windres
+WINDRES ?= windres
 endif
 
+LIBLZ4      = $(LIBLZ4_NAME).$(SHARED_EXT_VER)
+
 #determine if dev/nul based on host environment
 ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(shell $(UNAME))))
 VOID := /dev/null
@@ -108,4 +110,4 @@
 
 INSTALL_PROGRAM ?= $(INSTALL) -m 755
 INSTALL_DATA    ?= $(INSTALL) -m 644
-INSTALL_DIR     ?= $(INSTALL) -d -m 755
+MAKE_DIR        ?= $(INSTALL) -d -m 755
diff --git a/NEWS b/NEWS
index 0a56992..b6c5730 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,27 @@
+v1.10.0
+cli  : multithreading compression support: improves speed by X times threads allocated
+cli  : overlap decompression with i/o, improving speed by ~+60%
+cli  : support environment variables LZ4_CLEVEL and LZ4_NBWORKERS
+cli  : license of CLI more clearly labelled GPL-2.0-or-later
+cli  : fix: refuse to compress directories
+cli  : fix dictionary compression benchmark on multiple files
+cli  : change: no more implicit `stdout` (except when input is `stdin`)
+lib  : new level 2, offering mid-way performance (speed and compression)
+lib  : Improved lz4frame compression speed for small data (up to +160% at 1KB)
+lib  : Slightly faster (+5%) HC compression speed (levels 3-9), by @JunHe77
+lib  : dictionary compression support now in stable status
+lib  : lz4frame states can be safely reset and reused after a processing error (described by @QrczakMK)
+lib  : `lz4file` API improvements, by @vsolontsov-volant and @t-mat
+lib  : new experimental symbol `LZ4_compress_destSize_extState()`
+build: cmake minimum version raised to 3.5
+build: cmake improvements, by @foxeng, @Ohjurot, @LocalSpook, @teo-tsirpanis, @ur4t and @t-mat
+build: meson scripts are now hosted into `build/` directory, by @eli-schwartz
+build: meson improvements, by @tristan957
+build: Visual Studio solutions generated by `cmake` via scripts
+port : support for loongArch, risc-v, m68k, mips and sparc architectures
+port : improved Visual Studio compatibility, by @t-mat
+port : freestanding support improvements, by @t-mat
+
 v1.9.4
 perf : faster decoding speed (~+20%) on aarch64 platforms
 perf : faster decoding speed (~+70%) for -BD4 setting in CLI
@@ -9,6 +33,7 @@
 cli  : `--list` works on `stdin` input, by @Low-power
 cli  : `--no-crc` does not produce (compression) nor check (decompression) checksums
 cli  : fix: `--test` and `--list` produce an error code when parsing invalid input
+cli  : fix: `--test -m` does no longer create decompressed file artifacts
 cli  : fix: support skippable frames when passed via `stdin`, reported by @davidmankin
 build: fix: Makefile respects CFLAGS directives passed via environment variable
 build: `LZ4_FREESTANDING`, new build macro for freestanding environments, by @t-mat
diff --git a/README.md b/README.md
index b314e69..5ee643f 100644
--- a/README.md
+++ b/README.md
@@ -26,10 +26,8 @@
 
 |Branch      |Status   |
 |------------|---------|
-|dev         | [![Build Status][travisDevBadge]][travisLink]    [![Build status][AppveyorDevBadge]][AppveyorLink]                                         |
+|dev         | [![Build status][AppveyorDevBadge]][AppveyorLink]  |
 
-[travisDevBadge]: https://travis-ci.org/lz4/lz4.svg?branch=dev "Continuous Integration test suite"
-[travisLink]: https://travis-ci.org/lz4/lz4
 [AppveyorDevBadge]: https://ci.appveyor.com/api/projects/status/github/lz4/lz4?branch=dev&svg=true "Windows test suite"
 [AppveyorLink]: https://ci.appveyor.com/project/YannCollet/lz4-1lndh
 
@@ -62,7 +60,7 @@
 [zlib]: http://www.zlib.net/
 [Zstandard]: http://www.zstd.net/
 
-LZ4 is also compatible and optimized for x32 mode,
+LZ4 is also compatible and optimized for x32 mode (`-mx32`),
 for which it provides additional speed performance.
 
 
@@ -91,7 +89,7 @@
     cd vcpkg
     ./bootstrap-vcpkg.sh
     ./vcpkg integrate install
-    vcpkg install lz4
+    ./vcpkg.exe install lz4
 
 The LZ4 port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
 
@@ -118,3 +116,16 @@
 A list of known source ports is maintained on the [LZ4 Homepage].
 
 [LZ4 Homepage]: http://www.lz4.org
+
+### Packaging status
+
+Most distributions are bundled with a package manager
+which allows easy installation of both the `liblz4` library
+and the `lz4` command line interface.
+
+[![Packaging status](https://repology.org/badge/vertical-allrepos/lz4.svg)](https://repology.org/project/lz4/versions)
+
+
+### Special Thanks
+
+- Takayuki Matsuoka, aka @t-mat, for exceptional first-class support throughout the lifetime of this project
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..9be9aeb
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,17 @@
+# Security Policy
+
+If you have discovered a security vulnerability in this project, please report it
+privately. **Do not disclose it as a public issue.** This gives me time to work with you
+to fix the issue before public exposure, reducing the chance that the exploit will be
+used before a patch is released.
+
+Please submit the report by filling out
+[this form](https://github.com/lz4/lz4/security/advisories/new).
+
+Please provide the following information in your report:
+
+- A description of the vulnerability and its impact
+- How to reproduce the issue
+
+This project is maintained by a single maintainer on a reasonable-effort basis. As such,
+I ask that you give me 90 days to work on a fix before public exposure.
diff --git a/appveyor.yml b/appveyor.yml
index b4c27ef..6be66ae 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -2,14 +2,9 @@
 environment:
   matrix:
   - COMPILER: "gcc"
-    PLATFORM: "mingw64"
-  - COMPILER: "gcc"
     PLATFORM: "mingw32"
   - COMPILER: "visual"
     CONFIGURATION: "Debug"
-    PLATFORM: "x64"
-  - COMPILER: "visual"
-    CONFIGURATION: "Debug"
     PLATFORM: "Win32"
   - COMPILER: "visual"
     CONFIGURATION: "Release"
@@ -17,48 +12,53 @@
   - COMPILER: "visual"
     CONFIGURATION: "Release"
     PLATFORM: "Win32"
+  - COMPILER: "clang"
+    PLATFORM: "mingw64"
   - COMPILER: "gcc"
-    PLATFORM: "clang"
+    PLATFORM: "mingw64"
 
 install:
   - ECHO Installing %COMPILER% %PLATFORM% %CONFIGURATION%
   - MKDIR bin
-  - if [%COMPILER%]==[gcc] SET PATH_ORIGINAL=%PATH%
-  - if [%COMPILER%]==[gcc] (
+  - if [%COMPILER%]==[visual] (
+      if [%PLATFORM%]==[x64] (
+        SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;"
+      )
+    ) else (
       SET "PATH_MINGW32=c:\MinGW\bin;c:\MinGW\usr\bin" &&
       SET "PATH_MINGW64=c:\msys64\mingw64\bin;c:\msys64\usr\bin" &&
       COPY C:\MinGW\bin\mingw32-make.exe C:\MinGW\bin\make.exe &&
       COPY C:\MinGW\bin\gcc.exe C:\MinGW\bin\cc.exe
-    ) else (
-      IF [%PLATFORM%]==[x64] (SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;")
     )
 
 build_script:
-  - if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH_ORIGINAL%
-  - if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL%
-  - if [%PLATFORM%]==[clang] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL%
+  - if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH%
+  - if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH%
   - ECHO *** &&
       ECHO Building %COMPILER% %PLATFORM% %CONFIGURATION% &&
       ECHO ***
-  - if [%PLATFORM%]==[clang] (clang -v)
-  - if [%COMPILER%]==[gcc] (gcc -v)
   - if [%COMPILER%]==[gcc] (
-      echo ----- &&
+      echo ----- %TIME% &&
+      gcc -v &&
       make -v &&
       echo ----- &&
-      if not [%PLATFORM%]==[clang] (
-        make -C programs lz4 &&
-        make -C tests fullbench &&
-        make -C tests fuzzer &&
-        make -C lib lib V=1
-      ) ELSE (
-        make -C programs lz4 CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" &&
-        make -C tests fullbench CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" &&
-        make -C tests fuzzer CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" &&
-        make -C lib lib CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion"
-      )
+      make -j -C programs lz4 V=1 &&
+      make -j -C tests fullbench V=1 &&
+      make -j -C tests fuzzer V=1 &&
+      make -j -C lib lib V=1
     )
-  - if [%COMPILER%]==[gcc] if not [%PLATFORM%]==[clang] (
+  - if [%COMPILER%]==[clang] (
+      echo ----- %TIME% &&
+      clang -v &&
+      make -v &&
+      echo ----- &&
+      set CFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" &&
+      make -j -C programs lz4 CC=clang V=1    &&
+      make -j -C tests fullbench CC=clang V=1 &&
+      make -j -C tests fuzzer CC=clang V=1    &&
+      make -j -C lib lib CC=clang V=1
+    )
+  - if [%COMPILER%]==[gcc] (
       MKDIR bin\dll bin\static bin\example bin\include &&
       COPY tests\fullbench.c bin\example\ &&
       COPY lib\xxhash.c bin\example\ &&
@@ -67,7 +67,7 @@
       COPY lib\lz4hc.h bin\include\ &&
       COPY lib\lz4frame.h bin\include\ &&
       COPY lib\liblz4.a bin\static\liblz4_static.lib &&
-      COPY lib\dll\* bin\dll\ &&
+      COPY lib\liblz4.dll* bin\dll\ &&
       COPY lib\dll\example\Makefile bin\example\ &&
       COPY lib\dll\example\fullbench-dll.* bin\example\ &&
       COPY lib\dll\example\README.md bin\ &&
@@ -81,29 +81,22 @@
       7z.exe a -bb1 bin\lz4_x86.zip NEWS .\bin\lz4.exe .\bin\README.md .\bin\example .\bin\dll .\bin\static .\bin\include &&
       appveyor PushArtifact bin\lz4_x86.zip
     )
-  - if [%COMPILER%]==[gcc] (COPY tests\*.exe programs\)
   - if [%COMPILER%]==[visual] (
-      ECHO *** &&
-      ECHO *** Building Visual Studio 2010 %PLATFORM%\%CONFIGURATION% &&
-      ECHO *** &&
-      msbuild "build\VS2010\lz4.sln" %ADDITIONALPARAM% /m /verbosity:minimal /property:PlatformToolset=v100 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /p:EnableWholeProgramOptimization=true /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
-      ECHO *** &&
+      ECHO *** %TIME% &&
       ECHO *** Building Visual Studio 2012 %PLATFORM%\%CONFIGURATION% &&
       ECHO *** &&
-      msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
-      ECHO *** &&
+      msbuild "build\VS2022\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /property:Optimize=false /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
+      ECHO *** %TIME% &&
       ECHO *** Building Visual Studio 2013 %PLATFORM%\%CONFIGURATION% &&
       ECHO *** &&
-      msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v120 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
-      ECHO *** &&
-      ECHO *** Building Visual Studio 2015 %PLATFORM%\%CONFIGURATION% &&
-      ECHO *** &&
-      msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v140 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
-      COPY build\VS2010\bin\%PLATFORM%_%CONFIGURATION%\*.exe programs\
+      msbuild "build\VS2022\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v120 /property:Optimize=false /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" &&
+      COPY build\VS2022\bin\%PLATFORM%_%CONFIGURATION%\*.exe programs\
+    ) else (
+      COPY tests\*.exe programs\
     )
 
 test_script:
-  - ECHO *** &&
+  - ECHO *** %TIME% &&
       ECHO Testing %COMPILER% %PLATFORM% %CONFIGURATION% &&
       ECHO ***
   - if not [%COMPILER%]==[unknown] (
@@ -114,10 +107,11 @@
       lz4 -i1b10 lz4.exe &&
       lz4 -i1b15 lz4.exe &&
       echo ------- lz4 tested ------- &&
-      fullbench.exe -i1 fullbench.exe &&
-      echo trying to launch fuzzer.exe &&
-      fuzzer.exe -v -T30s
+      fullbench.exe -i0 fullbench.exe &&
+      echo Launching test program fuzzer.exe &&
+      fuzzer.exe -v -T20s
     )
+  - ECHO *** %TIME%
 
 artifacts:
   - path: bin\lz4_x64.zip
diff --git a/build/.gitignore b/build/.gitignore
index 69e1111..f0a2f9d 100644
--- a/build/.gitignore
+++ b/build/.gitignore
@@ -9,8 +9,10 @@
 ver*/
 VS2010/bin/
 VS2017/bin/
+VS*/bin/
 ipch
 
 # Fixup for lz4 project directories
 !VS2010/lz4
 !VS2017/lz4
+!VS*/lz4
diff --git a/build/README.md b/build/README.md
index d416aeb..d183edb 100644
--- a/build/README.md
+++ b/build/README.md
@@ -5,23 +5,12 @@
 
 The following projects are included with the lz4 distribution:
 - `cmake` - CMake project
-- `VS2010` - Visual Studio 2010 project (which also works well with Visual Studio 2012, 2013, 2015)
-- `VS2017` - Visual Studio 2017 project
+- `meson` - Meson project
+- `visual` - scripts to generate Visual Studio solutions from `cmake` script
+- `VS2022` - Visual Studio 2022 solution - will soon be deprecated, prefer `visual` generators
 
 
-#### How to compile lz4 with Visual Studio
-
-1. Install Visual Studio e.g. VS 2015 Community Edition (it's free).
-2. Download the latest version of lz4 from https://github.com/lz4/lz4/releases
-3. Decompress ZIP archive.
-4. Go to decompressed directory then to `build` then `VS2010` and open `lz4.sln`
-5. Visual Studio will ask about converting VS2010 project to VS2015 and you should agree.
-6. Change `Debug` to `Release` and if you have 64-bit Windows change also `Win32` to `x64`.
-7. Press F7 on keyboard or select `BUILD` from the menu bar and choose `Build Solution`.
-8. If compilation will be fine a compiled executable will be in `build\VS2010\bin\x64_Release\lz4.exe`
-
-
-#### Projects available within lz4.sln
+#### Projects available within VS2022\lz4.sln
 
 The Visual Studio solution file `lz4.sln` contains many projects that will be compiled to the
 `build\VS2010\bin\$(Platform)_$(Configuration)` directory. For example `lz4` set to `x64` and
diff --git a/build/VS2010/datagen/datagen.vcxproj b/build/VS2010/datagen/datagen.vcxproj
deleted file mode 100644
index e24f961..0000000
--- a/build/VS2010/datagen/datagen.vcxproj
+++ /dev/null
@@ -1,169 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{D745AE2F-596A-403A-9B91-81A8C6779243}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>datagen</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\programs\datagen.c" />
-    <ClCompile Include="..\..\..\tests\datagencli.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\programs\datagen.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
diff --git a/build/VS2010/frametest/frametest.vcxproj b/build/VS2010/frametest/frametest.vcxproj
deleted file mode 100644
index 3196768..0000000
--- a/build/VS2010/frametest/frametest.vcxproj
+++ /dev/null
@@ -1,176 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>frametest</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\frametest.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
diff --git a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj b/build/VS2010/fullbench-dll/fullbench-dll.vcxproj
deleted file mode 100644
index 8f503f5..0000000
--- a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj
+++ /dev/null
@@ -1,180 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{13992FD2-077E-4954-B065-A428198201A9}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fullbench-dll</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fullbench.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2010/fullbench/fullbench.vcxproj b/build/VS2010/fullbench/fullbench.vcxproj
deleted file mode 100644
index aa67431..0000000
--- a/build/VS2010/fullbench/fullbench.vcxproj
+++ /dev/null
@@ -1,176 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fullbench</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fullbench.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
diff --git a/build/VS2010/fuzzer/fuzzer.vcxproj b/build/VS2010/fuzzer/fuzzer.vcxproj
deleted file mode 100644
index 21cbf56..0000000
--- a/build/VS2010/fuzzer/fuzzer.vcxproj
+++ /dev/null
@@ -1,173 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{18B9F1A7-9C66-4352-898B-30804DADE0FD}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fuzzer</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fuzzer.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
diff --git a/build/VS2010/liblz4-dll/liblz4-dll.rc b/build/VS2010/liblz4-dll/liblz4-dll.rc
deleted file mode 100644
index e089c24..0000000
--- a/build/VS2010/liblz4-dll/liblz4-dll.rc
+++ /dev/null
@@ -1,51 +0,0 @@
-// Microsoft Visual C++ generated resource script.
-//
-
-#include "lz4.h" /* LZ4_VERSION_STRING */
-#define APSTUDIO_READONLY_SYMBOLS
-#include "verrsrc.h"
-#undef APSTUDIO_READONLY_SYMBOLS
-
-
-#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-LANGUAGE 9, 1
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO     VERSIONINFO
-  FILEVERSION       LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
-  PRODUCTVERSION    LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
- FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
-#ifdef _DEBUG
- FILEFLAGS VS_FF_DEBUG
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS VOS_NT_WINDOWS32
- FILETYPE VFT_DLL
- FILESUBTYPE VFT2_UNKNOWN
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "040904B0"
-        BEGIN
-            VALUE "CompanyName", "Yann Collet"
-            VALUE "FileDescription", "Extremely fast compression"
-            VALUE "FileVersion", LZ4_VERSION_STRING
-            VALUE "InternalName", "lz4.dll"
-            VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet"
-            VALUE "OriginalFilename", "lz4.dll"
-            VALUE "ProductName", "LZ4"
-            VALUE "ProductVersion", LZ4_VERSION_STRING
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x0409, 1200
-    END
-END
-
-#endif
diff --git a/build/VS2010/liblz4-dll/liblz4-dll.vcxproj b/build/VS2010/liblz4-dll/liblz4-dll.vcxproj
deleted file mode 100644
index 56ec3b9..0000000
--- a/build/VS2010/liblz4-dll/liblz4-dll.vcxproj
+++ /dev/null
@@ -1,179 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{9800039D-4AAA-43A4-BB78-FEF6F4836927}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>liblz4-dll</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-    <ProjectName>liblz4-dll</ProjectName>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="liblz4-dll.rc" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2010/liblz4/liblz4.vcxproj b/build/VS2010/liblz4/liblz4.vcxproj
deleted file mode 100644
index 61ea159..0000000
--- a/build/VS2010/liblz4/liblz4.vcxproj
+++ /dev/null
@@ -1,175 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>liblz4</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
diff --git a/build/VS2010/lz4.sln b/build/VS2010/lz4.sln
deleted file mode 100644
index 78f223b..0000000
--- a/build/VS2010/lz4.sln
+++ /dev/null
@@ -1,98 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Express 2012 for Windows Desktop
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{E30329AC-0057-4FE0-8FDA-7F650D398C4C}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "liblz4\liblz4.vcxproj", "{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcxproj", "{18B9F1A7-9C66-4352-898B-30804DADE0FD}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "frametest", "frametest\frametest.vcxproj", "{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{D745AE2F-596A-403A-9B91-81A8C6779243}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}"
-	ProjectSection(ProjectDependencies) = postProject
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927} = {9800039D-4AAA-43A4-BB78-FEF6F4836927}
-	EndProjectSection
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Win32 = Debug|Win32
-		Debug|x64 = Debug|x64
-		Release|Win32 = Release|Win32
-		Release|x64 = Release|x64
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.ActiveCfg = Debug|Win32
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.Build.0 = Debug|Win32
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.ActiveCfg = Debug|x64
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.Build.0 = Debug|x64
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.ActiveCfg = Release|Win32
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.Build.0 = Release|Win32
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.ActiveCfg = Release|x64
-		{E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.Build.0 = Release|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.ActiveCfg = Debug|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.Build.0 = Debug|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.ActiveCfg = Debug|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.Build.0 = Debug|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.ActiveCfg = Release|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.Build.0 = Release|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.ActiveCfg = Release|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.Build.0 = Release|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.ActiveCfg = Debug|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.Build.0 = Debug|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.ActiveCfg = Debug|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.Build.0 = Debug|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.ActiveCfg = Release|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.Build.0 = Release|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.ActiveCfg = Release|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.Build.0 = Release|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.ActiveCfg = Debug|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.Build.0 = Debug|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.ActiveCfg = Debug|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.Build.0 = Debug|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.ActiveCfg = Release|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.Build.0 = Release|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.ActiveCfg = Release|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.Build.0 = Release|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.Build.0 = Debug|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.ActiveCfg = Debug|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.Build.0 = Debug|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.ActiveCfg = Release|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.Build.0 = Release|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.ActiveCfg = Release|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.Build.0 = Release|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.ActiveCfg = Debug|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.Build.0 = Debug|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.ActiveCfg = Debug|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.Build.0 = Debug|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.ActiveCfg = Release|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.Build.0 = Release|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.ActiveCfg = Release|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.Build.0 = Release|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.ActiveCfg = Debug|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.Build.0 = Debug|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.ActiveCfg = Debug|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.Build.0 = Debug|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.ActiveCfg = Release|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.Build.0 = Release|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.ActiveCfg = Release|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.Build.0 = Release|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-EndGlobal
diff --git a/build/VS2010/lz4/lz4.vcxproj b/build/VS2010/lz4/lz4.vcxproj
deleted file mode 100644
index de7a714..0000000
--- a/build/VS2010/lz4/lz4.vcxproj
+++ /dev/null
@@ -1,189 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{E30329AC-0057-4FE0-8FDA-7F650D398C4C}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>lz4</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalDependencies>setargv.obj;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalDependencies>setargv.obj;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalDependencies>setargv.obj;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalDependencies>setargv.obj;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-    <ClInclude Include="..\..\..\programs\datagen.h" />
-    <ClInclude Include="..\..\..\programs\bench.h" />
-    <ClInclude Include="..\..\..\programs\lz4io.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\programs\datagen.c" />
-    <ClCompile Include="..\..\..\programs\bench.c" />
-    <ClCompile Include="..\..\..\programs\lz4cli.c" />
-    <ClCompile Include="..\..\..\programs\lz4io.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="lz4.rc" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/datagen/datagen.vcxproj b/build/VS2017/datagen/datagen.vcxproj
deleted file mode 100644
index 30e159e..0000000
--- a/build/VS2017/datagen/datagen.vcxproj
+++ /dev/null
@@ -1,173 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{D745AE2F-596A-403A-9B91-81A8C6779243}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>datagen</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\programs\datagen.c" />
-    <ClCompile Include="..\..\..\tests\datagencli.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\programs\datagen.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/frametest/frametest.vcxproj b/build/VS2017/frametest/frametest.vcxproj
deleted file mode 100644
index a3a403d..0000000
--- a/build/VS2017/frametest/frametest.vcxproj
+++ /dev/null
@@ -1,180 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>frametest</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\frametest.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/fullbench-dll/fullbench-dll.vcxproj b/build/VS2017/fullbench-dll/fullbench-dll.vcxproj
deleted file mode 100644
index d54a8d7..0000000
--- a/build/VS2017/fullbench-dll/fullbench-dll.vcxproj
+++ /dev/null
@@ -1,184 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{13992FD2-077E-4954-B065-A428198201A9}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fullbench-dll</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-      <AdditionalLibraryDirectories>$(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
-      <AdditionalDependencies>liblz4.lib;%(AdditionalDependencies)</AdditionalDependencies>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fullbench.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/fullbench/fullbench.vcxproj b/build/VS2017/fullbench/fullbench.vcxproj
deleted file mode 100644
index 54c9743..0000000
--- a/build/VS2017/fullbench/fullbench.vcxproj
+++ /dev/null
@@ -1,180 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fullbench</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fullbench.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/fuzzer/fuzzer.vcxproj b/build/VS2017/fuzzer/fuzzer.vcxproj
deleted file mode 100644
index aa6fe42..0000000
--- a/build/VS2017/fuzzer/fuzzer.vcxproj
+++ /dev/null
@@ -1,177 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{18B9F1A7-9C66-4352-898B-30804DADE0FD}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>fuzzer</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <SubSystem>Console</SubSystem>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-    <ClCompile Include="..\..\..\tests\fuzzer.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/liblz4-dll/liblz4-dll.rc b/build/VS2017/liblz4-dll/liblz4-dll.rc
deleted file mode 100644
index e089c24..0000000
--- a/build/VS2017/liblz4-dll/liblz4-dll.rc
+++ /dev/null
@@ -1,51 +0,0 @@
-// Microsoft Visual C++ generated resource script.
-//
-
-#include "lz4.h" /* LZ4_VERSION_STRING */
-#define APSTUDIO_READONLY_SYMBOLS
-#include "verrsrc.h"
-#undef APSTUDIO_READONLY_SYMBOLS
-
-
-#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-LANGUAGE 9, 1
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO     VERSIONINFO
-  FILEVERSION       LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
-  PRODUCTVERSION    LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
- FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
-#ifdef _DEBUG
- FILEFLAGS VS_FF_DEBUG
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS VOS_NT_WINDOWS32
- FILETYPE VFT_DLL
- FILESUBTYPE VFT2_UNKNOWN
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "040904B0"
-        BEGIN
-            VALUE "CompanyName", "Yann Collet"
-            VALUE "FileDescription", "Extremely fast compression"
-            VALUE "FileVersion", LZ4_VERSION_STRING
-            VALUE "InternalName", "lz4.dll"
-            VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet"
-            VALUE "OriginalFilename", "lz4.dll"
-            VALUE "ProductName", "LZ4"
-            VALUE "ProductVersion", LZ4_VERSION_STRING
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x0409, 1200
-    END
-END
-
-#endif
diff --git a/build/VS2017/liblz4-dll/liblz4-dll.vcxproj b/build/VS2017/liblz4-dll/liblz4-dll.vcxproj
deleted file mode 100644
index 8e7ee3b..0000000
--- a/build/VS2017/liblz4-dll/liblz4-dll.vcxproj
+++ /dev/null
@@ -1,183 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{9800039D-4AAA-43A4-BB78-FEF6F4836927}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>liblz4-dll</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-    <ProjectName>liblz4-dll</ProjectName>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>DynamicLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <ResourceCompile Include="liblz4-dll.rc" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/liblz4/liblz4.vcxproj b/build/VS2017/liblz4/liblz4.vcxproj
deleted file mode 100644
index 948f7db..0000000
--- a/build/VS2017/liblz4/liblz4.vcxproj
+++ /dev/null
@@ -1,179 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup Label="ProjectConfigurations">
-    <ProjectConfiguration Include="Debug|Win32">
-      <Configuration>Debug</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Debug|x64">
-      <Configuration>Debug</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|Win32">
-      <Configuration>Release</Configuration>
-      <Platform>Win32</Platform>
-    </ProjectConfiguration>
-    <ProjectConfiguration Include="Release|x64">
-      <Configuration>Release</Configuration>
-      <Platform>x64</Platform>
-    </ProjectConfiguration>
-  </ItemGroup>
-  <PropertyGroup Label="Globals">
-    <ProjectGuid>{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}</ProjectGuid>
-    <Keyword>Win32Proj</Keyword>
-    <RootNamespace>liblz4</RootNamespace>
-    <OutDir>$(SolutionDir)bin\$(Platform)_$(Configuration)\</OutDir>
-    <IntDir>$(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\</IntDir>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>true</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
-    <UseDebugLibraries>false</UseDebugLibraries>
-    <CharacterSet>Unicode</CharacterSet>
-    <WholeProgramOptimization Condition="'$(EnableWholeProgramOptimization)'=='true'">true</WholeProgramOptimization>
-    <PlatformToolset>v141</PlatformToolset>
-  </PropertyGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
-  <ImportGroup Label="ExtensionSettings">
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
-    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
-  </ImportGroup>
-  <PropertyGroup Label="UserMacros" />
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <LinkIncremental>true</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-  </PropertyGroup>
-  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <LinkIncremental>false</LinkIncremental>
-    <TargetName>liblz4_static</TargetName>
-    <IncludePath>$(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath);</IncludePath>
-    <RunCodeAnalysis>true</RunCodeAnalysis>
-  </PropertyGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
-    <ClCompile>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <WarningLevel>Level4</WarningLevel>
-      <Optimization>Disabled</Optimization>
-      <PreprocessorDefinitions>WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>true</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreadedDebug</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>false</EnablePREfast>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
-    <ClCompile>
-      <WarningLevel>Level4</WarningLevel>
-      <PrecompiledHeader>
-      </PrecompiledHeader>
-      <Optimization>MaxSpeed</Optimization>
-      <FunctionLevelLinking>true</FunctionLevelLinking>
-      <IntrinsicFunctions>true</IntrinsicFunctions>
-      <PreprocessorDefinitions>WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
-      <TreatWarningAsError>false</TreatWarningAsError>
-      <EnablePREfast>true</EnablePREfast>
-      <AdditionalOptions>/analyze:stacksize295252 %(AdditionalOptions)</AdditionalOptions>
-      <RuntimeLibrary Condition="'$(UseStaticCRT)'=='true'">MultiThreaded</RuntimeLibrary>
-    </ClCompile>
-    <Link>
-      <GenerateDebugInformation>true</GenerateDebugInformation>
-      <EnableCOMDATFolding>true</EnableCOMDATFolding>
-      <OptimizeReferences>true</OptimizeReferences>
-    </Link>
-  </ItemDefinitionGroup>
-  <ItemGroup>
-    <ClInclude Include="..\..\..\lib\lz4.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame.h" />
-    <ClInclude Include="..\..\..\lib\lz4frame_static.h" />
-    <ClInclude Include="..\..\..\lib\lz4hc.h" />
-    <ClInclude Include="..\..\..\lib\xxhash.h" />
-  </ItemGroup>
-  <ItemGroup>
-    <ClCompile Include="..\..\..\lib\lz4.c" />
-    <ClCompile Include="..\..\..\lib\lz4frame.c" />
-    <ClCompile Include="..\..\..\lib\lz4hc.c" />
-    <ClCompile Include="..\..\..\lib\xxhash.c" />
-  </ItemGroup>
-  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
-  <ImportGroup Label="ExtensionTargets">
-  </ImportGroup>
-</Project>
\ No newline at end of file
diff --git a/build/VS2017/lz4.sln b/build/VS2017/lz4.sln
deleted file mode 100644
index 6a2779f..0000000
--- a/build/VS2017/lz4.sln
+++ /dev/null
@@ -1,103 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.28307.271
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "liblz4\liblz4.vcxproj", "{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcxproj", "{18B9F1A7-9C66-4352-898B-30804DADE0FD}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "frametest", "frametest\frametest.vcxproj", "{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{D745AE2F-596A-403A-9B91-81A8C6779243}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}"
-	ProjectSection(ProjectDependencies) = postProject
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927} = {9800039D-4AAA-43A4-BB78-FEF6F4836927}
-	EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{60A3115E-B988-41EE-8815-F4D4F253D866}"
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Win32 = Debug|Win32
-		Debug|x64 = Debug|x64
-		Release|Win32 = Release|Win32
-		Release|x64 = Release|x64
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.ActiveCfg = Debug|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.Build.0 = Debug|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.ActiveCfg = Debug|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.Build.0 = Debug|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.ActiveCfg = Release|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.Build.0 = Release|Win32
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.ActiveCfg = Release|x64
-		{9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.Build.0 = Release|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.ActiveCfg = Debug|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.Build.0 = Debug|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.ActiveCfg = Debug|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.Build.0 = Debug|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.ActiveCfg = Release|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.Build.0 = Release|Win32
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.ActiveCfg = Release|x64
-		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.Build.0 = Release|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.ActiveCfg = Debug|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.Build.0 = Debug|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.ActiveCfg = Debug|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.Build.0 = Debug|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.ActiveCfg = Release|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.Build.0 = Release|Win32
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.ActiveCfg = Release|x64
-		{18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.Build.0 = Release|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.Build.0 = Debug|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.ActiveCfg = Debug|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.Build.0 = Debug|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.ActiveCfg = Release|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.Build.0 = Release|Win32
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.ActiveCfg = Release|x64
-		{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.Build.0 = Release|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.ActiveCfg = Debug|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.Build.0 = Debug|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.ActiveCfg = Debug|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.Build.0 = Debug|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.ActiveCfg = Release|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.Build.0 = Release|Win32
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.ActiveCfg = Release|x64
-		{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.Build.0 = Release|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.ActiveCfg = Debug|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.Build.0 = Debug|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.ActiveCfg = Debug|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.Build.0 = Debug|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.ActiveCfg = Release|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.Build.0 = Release|Win32
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.ActiveCfg = Release|x64
-		{D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.Build.0 = Release|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64
-		{13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|Win32.ActiveCfg = Debug|Win32
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|Win32.Build.0 = Debug|Win32
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|x64.ActiveCfg = Debug|x64
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|x64.Build.0 = Debug|x64
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Release|Win32.ActiveCfg = Release|Win32
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Release|Win32.Build.0 = Release|Win32
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Release|x64.ActiveCfg = Release|x64
-		{60A3115E-B988-41EE-8815-F4D4F253D866}.Release|x64.Build.0 = Release|x64
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-	GlobalSection(ExtensibilityGlobals) = postSolution
-		SolutionGuid = {BBC259B2-BABF-47CD-8A6A-7B8318A803AC}
-	EndGlobalSection
-EndGlobal
diff --git a/build/VS2017/lz4/lz4.rc b/build/VS2017/lz4/lz4.rc
deleted file mode 100644
index 5eec36b..0000000
--- a/build/VS2017/lz4/lz4.rc
+++ /dev/null
@@ -1,51 +0,0 @@
-// Microsoft Visual C++ generated resource script.
-//
-
-#include "lz4.h" /* LZ4_VERSION_STRING */
-#define APSTUDIO_READONLY_SYMBOLS
-#include "verrsrc.h"
-#undef APSTUDIO_READONLY_SYMBOLS
-
-
-#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-LANGUAGE 9, 1
-
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO     VERSIONINFO
-  FILEVERSION       LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
-  PRODUCTVERSION    LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0
- FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
-#ifdef _DEBUG
- FILEFLAGS VS_FF_DEBUG
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS VOS_NT_WINDOWS32
- FILETYPE VFT_DLL
- FILESUBTYPE VFT2_UNKNOWN
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "040904B0"
-        BEGIN
-            VALUE "CompanyName", "Yann Collet"
-            VALUE "FileDescription", "Extremely fast compression"
-            VALUE "FileVersion", LZ4_VERSION_STRING
-            VALUE "InternalName", "lz4.exe"
-            VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet"
-            VALUE "OriginalFilename", "lz4.exe"
-            VALUE "ProductName", "LZ4"
-            VALUE "ProductVersion", LZ4_VERSION_STRING
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x0409, 1200
-    END
-END
-
-#endif
diff --git a/build/VS2022/_build.bat b/build/VS2022/_build.bat
new file mode 100644
index 0000000..2c2eb57
--- /dev/null
+++ b/build/VS2022/_build.bat
@@ -0,0 +1,39 @@
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+rem https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference
+
+set "sln=lz4.sln"
+
+@rem set "Configuration=Debug"
+@rem set "Platform=Win32"
+
+set "BIN=.\bin\!Platform!_!Configuration!"
+rmdir /S /Q "!BIN!" 2>nul
+echo msbuild "%sln%" /p:Configuration=!Configuration! /p:Platform=!Platform!
+msbuild "%sln%"                          ^
+        /nologo                          ^
+        /v:minimal                       ^
+        /m                               ^
+        /p:Configuration=!Configuration! ^
+        /p:Platform=!Platform!           ^
+        /t:Clean,Build                   ^
+        || goto :ERROR
+
+if not exist "!BIN!\datagen.exe"       ( echo FAIL: "!BIN!\datagen.exe"       && goto :ERROR )
+if not exist "!BIN!\frametest.exe"     ( echo FAIL: "!BIN!\frametest.exe"     && goto :ERROR )
+if not exist "!BIN!\fullbench-dll.exe" ( echo FAIL: "!BIN!\fullbench-dll.exe" && goto :ERROR )
+if not exist "!BIN!\fullbench.exe"     ( echo FAIL: "!BIN!\fullbench.exe"     && goto :ERROR )
+if not exist "!BIN!\fuzzer.exe"        ( echo FAIL: "!BIN!\fuzzer.exe"        && goto :ERROR )
+if not exist "!BIN!\liblz4.dll"        ( echo FAIL: "!BIN!\liblz4.dll"        && goto :ERROR )
+if not exist "!BIN!\liblz4.lib"        ( echo FAIL: "!BIN!\liblz4.lib"        && goto :ERROR )
+if not exist "!BIN!\liblz4_static.lib" ( echo FAIL: "!BIN!\liblz4_static.lib" && goto :ERROR )
+if not exist "!BIN!\lz4.exe"           ( echo FAIL: "!BIN!\lz4.exe"           && goto :ERROR )
+
+set /a errorno=0
+goto :END
+
+:ERROR
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/_setup.bat b/build/VS2022/_setup.bat
new file mode 100644
index 0000000..b4dda51
--- /dev/null
+++ b/build/VS2022/_setup.bat
@@ -0,0 +1,35 @@
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+rem https://github.com/Microsoft/vswhere
+rem https://github.com/microsoft/vswhere/wiki/Find-VC#batch
+
+set "vswhere=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
+if not exist "%vswhere%" (
+  echo Failed to find "vswhere.exe".  Please install the latest version of Visual Studio.
+  goto :ERROR
+)
+
+set "InstallDir="
+for /f "usebackq tokens=*" %%i in (
+  `"%vswhere%" -latest                                                     ^
+               -products *                                                 ^
+               -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ^
+               -property installationPath`
+) do (
+  set "InstallDir=%%i"
+)
+if "%InstallDir%" == "" (
+  echo Failed to find Visual C++.  Please install the latest version of Visual C++.
+  goto :ERROR
+)
+
+call "%InstallDir%\VC\Auxiliary\Build\vcvars64.bat" || goto :ERROR
+
+set /a errorno=0
+goto :END
+
+:ERROR
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/_test.bat b/build/VS2022/_test.bat
new file mode 100644
index 0000000..4614fa9
--- /dev/null
+++ b/build/VS2022/_test.bat
@@ -0,0 +1,38 @@
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+@rem set "Configuration=Debug"
+@rem set "Platform=Win32"
+
+set "BIN=.\bin\!Platform!_!Configuration!"
+set "TEST_FILES=..\..\tests\COPYING"
+
+echo !BIN!\lz4 -h
+     !BIN!\lz4 -h	|| goto :ERROR
+
+echo !BIN!\lz4 -i1b
+     !BIN!\lz4 -i1b	|| goto :ERROR
+
+echo !BIN!\lz4 -i1b5
+     !BIN!\lz4 -i1b5	|| goto :ERROR
+
+echo !BIN!\lz4 -i1b10
+     !BIN!\lz4 -i1b10	|| goto :ERROR
+
+echo !BIN!\lz4 -i1b15
+     !BIN!\lz4 -i1b15	|| goto :ERROR
+     
+echo fullbench
+!BIN!\fullbench.exe --no-prompt -i1 %TEST_FILES%	|| goto :ERROR
+
+echo fuzzer
+!BIN!\fuzzer.exe -v -T30s				|| goto :ERROR
+
+
+set /a errorno=0
+goto :END
+
+:ERROR
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/build-and-test-win32-debug.bat b/build/VS2022/build-and-test-win32-debug.bat
new file mode 100644
index 0000000..e745f87
--- /dev/null
+++ b/build/VS2022/build-and-test-win32-debug.bat
@@ -0,0 +1,26 @@
+@setlocal enabledelayedexpansion
+@echo off
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+call _setup.bat || goto :ERROR
+
+set "Configuration=Debug"
+set "Platform=Win32"
+
+call _build.bat || goto :ERROR
+call _test.bat  || goto :ERROR
+
+
+echo Build Status -%esc%[92m SUCCEEDED %esc%[0m
+set /a errorno=0
+goto :END
+
+
+:ERROR
+echo Abort by error.
+echo Build Status -%esc%[91m ERROR %esc%[0m
+
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/build-and-test-win32-release.bat b/build/VS2022/build-and-test-win32-release.bat
new file mode 100644
index 0000000..f21007b
--- /dev/null
+++ b/build/VS2022/build-and-test-win32-release.bat
@@ -0,0 +1,26 @@
+@setlocal enabledelayedexpansion
+@echo off
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+call _setup.bat || goto :ERROR
+
+set "Configuration=Release"
+set "Platform=Win32"
+
+call _build.bat || goto :ERROR
+call _test.bat  || goto :ERROR
+
+
+echo Build Status -%esc%[92m SUCCEEDED %esc%[0m
+set /a errorno=0
+goto :END
+
+
+:ERROR
+echo Abort by error.
+echo Build Status -%esc%[91m ERROR %esc%[0m
+
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/build-and-test-x64-debug.bat b/build/VS2022/build-and-test-x64-debug.bat
new file mode 100644
index 0000000..9d64a6f
--- /dev/null
+++ b/build/VS2022/build-and-test-x64-debug.bat
@@ -0,0 +1,26 @@
+@setlocal enabledelayedexpansion
+@echo off
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+call _setup.bat || goto :ERROR
+
+set "Configuration=Debug"
+set "Platform=x64"
+
+call _build.bat || goto :ERROR
+call _test.bat  || goto :ERROR
+
+
+echo Build Status -%esc%[92m SUCCEEDED %esc%[0m
+set /a errorno=0
+goto :END
+
+
+:ERROR
+echo Abort by error.
+echo Build Status -%esc%[91m ERROR %esc%[0m
+
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/build-and-test-x64-release.bat b/build/VS2022/build-and-test-x64-release.bat
new file mode 100644
index 0000000..3ebb18f
--- /dev/null
+++ b/build/VS2022/build-and-test-x64-release.bat
@@ -0,0 +1,26 @@
+@setlocal enabledelayedexpansion
+@echo off
+set /a errorno=1
+for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E"
+
+call _setup.bat || goto :ERROR
+
+set "Configuration=Release"
+set "Platform=x64"
+
+call _build.bat || goto :ERROR
+call _test.bat  || goto :ERROR
+
+
+echo Build Status -%esc%[92m SUCCEEDED %esc%[0m
+set /a errorno=0
+goto :END
+
+
+:ERROR
+echo Abort by error.
+echo Build Status -%esc%[91m ERROR %esc%[0m
+
+
+:END
+exit /B %errorno%
diff --git a/build/VS2022/datagen/datagen.vcxproj b/build/VS2022/datagen/datagen.vcxproj
index 69034d4..a65a5d5 100644
--- a/build/VS2022/datagen/datagen.vcxproj
+++ b/build/VS2022/datagen/datagen.vcxproj
@@ -161,13 +161,17 @@
     </Link>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="..\..\..\programs\datagen.c" />
+    <ClCompile Include="..\..\..\programs\lorem.c" />
+    <ClCompile Include="..\..\..\tests\datagen.c" />
     <ClCompile Include="..\..\..\tests\datagencli.c" />
+    <ClCompile Include="..\..\..\tests\loremOut.c" />
   </ItemGroup>
   <ItemGroup>
-    <ClInclude Include="..\..\..\programs\datagen.h" />
+    <ClInclude Include="..\..\..\programs\lorem.h" />
+    <ClInclude Include="..\..\..\tests\datagen.h" />
+    <ClInclude Include="..\..\..\tests\loremOut.h" />
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/build/VS2022/lz4.sln b/build/VS2022/lz4.sln
index 6a2779f..10f8ec1 100644
--- a/build/VS2022/lz4.sln
+++ b/build/VS2022/lz4.sln
@@ -1,6 +1,6 @@
 Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.28307.271
+# Visual Studio Version 17
+VisualStudioVersion = 17.6.33712.159
 MinimumVisualStudioVersion = 10.0.40219.1
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}"
 EndProject
@@ -20,6 +20,9 @@
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{60A3115E-B988-41EE-8815-F4D4F253D866}"
+	ProjectSection(ProjectDependencies) = postProject
+		{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} = {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}
+	EndProjectSection
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/build/VS2010/lz4/lz4.rc b/build/VS2022/lz4/lz4.rc
similarity index 100%
rename from build/VS2010/lz4/lz4.rc
rename to build/VS2022/lz4/lz4.rc
diff --git a/build/VS2017/lz4/lz4.vcxproj b/build/VS2022/lz4/lz4.vcxproj
similarity index 83%
rename from build/VS2017/lz4/lz4.vcxproj
rename to build/VS2022/lz4/lz4.vcxproj
index f16c1ec..3c964b4 100644
--- a/build/VS2017/lz4/lz4.vcxproj
+++ b/build/VS2022/lz4/lz4.vcxproj
@@ -22,32 +22,32 @@
     <VCProjectVersion>15.0</VCProjectVersion>
     <ProjectGuid>{60A3115E-B988-41EE-8815-F4D4F253D866}</ProjectGuid>
     <RootNamespace>lz4</RootNamespace>
-    <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
+    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v141</PlatformToolset>
+    <PlatformToolset>v143</PlatformToolset>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>false</UseDebugLibraries>
-    <PlatformToolset>v141</PlatformToolset>
+    <PlatformToolset>v143</PlatformToolset>
     <WholeProgramOptimization>false</WholeProgramOptimization>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
-    <PlatformToolset>v141</PlatformToolset>
+    <PlatformToolset>v143</PlatformToolset>
     <CharacterSet>MultiByte</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     <UseDebugLibraries>false</UseDebugLibraries>
-    <PlatformToolset>v141</PlatformToolset>
+    <PlatformToolset>v143</PlatformToolset>
     <WholeProgramOptimization>true</WholeProgramOptimization>
     <CharacterSet>MultiByte</CharacterSet>
   </PropertyGroup>
@@ -105,6 +105,8 @@
       <SubSystem>Console</SubSystem>
       <OptimizeReferences>false</OptimizeReferences>
       <EnableCOMDATFolding>false</EnableCOMDATFolding>
+      <AdditionalLibraryDirectories>$(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
     </Link>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@@ -114,6 +116,10 @@
       <SDLCheck>true</SDLCheck>
       <ConformanceMode>true</ConformanceMode>
     </ClCompile>
+    <Link>
+      <AdditionalLibraryDirectories>$(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
     <ClCompile>
@@ -130,6 +136,8 @@
       <OptimizeReferences>true</OptimizeReferences>
       <GenerateDebugInformation>true</GenerateDebugInformation>
       <SubSystem>Console</SubSystem>
+      <AdditionalLibraryDirectories>$(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
     </Link>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
@@ -144,6 +152,8 @@
     <Link>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalLibraryDirectories>$(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)</AdditionalDependencies>
     </Link>
   </ItemDefinitionGroup>
   <ItemGroup>
@@ -152,9 +162,12 @@
     <ClCompile Include="..\..\..\lib\lz4hc.c" />
     <ClCompile Include="..\..\..\lib\xxhash.c" />
     <ClCompile Include="..\..\..\programs\bench.c" />
-    <ClCompile Include="..\..\..\programs\datagen.c" />
+    <ClCompile Include="..\..\..\programs\lorem.c" />
     <ClCompile Include="..\..\..\programs\lz4cli.c" />
     <ClCompile Include="..\..\..\programs\lz4io.c" />
+    <ClCompile Include="..\..\..\programs\threadpool.c" />
+    <ClCompile Include="..\..\..\programs\timefn.c" />
+    <ClCompile Include="..\..\..\programs\util.c" />
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="..\..\..\lib\lz4.h" />
@@ -163,8 +176,9 @@
     <ClInclude Include="..\..\..\lib\lz4hc.h" />
     <ClInclude Include="..\..\..\lib\xxhash.h" />
     <ClInclude Include="..\..\..\programs\bench.h" />
-    <ClInclude Include="..\..\..\programs\datagen.h" />
+    <ClInclude Include="..\..\..\programs\lorem.h" />
     <ClInclude Include="..\..\..\programs\lz4io.h" />
+    <ClInclude Include="..\..\..\programs\util.h" />
   </ItemGroup>
   <ItemGroup>
     <ResourceCompile Include="lz4.rc" />
diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index eb7007b..c372733 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -6,48 +6,43 @@
 # any warranty.
 #
 # For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
-#
-# LZ4's CMake support is maintained by Evan Nemerson; when filing
-# bugs please mention @nemequ to make sure I see it.
 
-cmake_minimum_required(VERSION 2.8.12)
+
+cmake_minimum_required(VERSION 3.5)
 
 set(LZ4_TOP_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../..")
 
 # Parse version information
-file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MAJOR REGEX "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$")
-string(REGEX REPLACE "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MAJOR "${LZ4_VERSION_MAJOR}")
-file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MINOR REGEX "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$")
-string(REGEX REPLACE "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MINOR "${LZ4_VERSION_MINOR}")
-file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_RELEASE REGEX "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$")
-string(REGEX REPLACE "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$" "\\1" LZ4_VERSION_RELEASE "${LZ4_VERSION_RELEASE}")
+function(parse_lz4_version VERSION_TYPE)
+    file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" version_line REGEX "^#define LZ4_VERSION_${VERSION_TYPE} +([0-9]+).*$")
+    string(REGEX REPLACE "^#define LZ4_VERSION_${VERSION_TYPE} +([0-9]+).*$" "\\1" version_number "${version_line}")
+    set(LZ4_VERSION_${VERSION_TYPE} ${version_number} PARENT_SCOPE)
+endfunction()
+
+foreach(version_type IN ITEMS MAJOR MINOR RELEASE)
+    parse_lz4_version(${version_type})
+endforeach()
+
 set(LZ4_VERSION_STRING "${LZ4_VERSION_MAJOR}.${LZ4_VERSION_MINOR}.${LZ4_VERSION_RELEASE}")
 mark_as_advanced(LZ4_VERSION_STRING LZ4_VERSION_MAJOR LZ4_VERSION_MINOR LZ4_VERSION_RELEASE)
 
-if("${CMAKE_VERSION}" VERSION_LESS "3.0")
-  project(LZ4 C)
-else()
-  cmake_policy (SET CMP0048 NEW)
-  project(LZ4
-    VERSION ${LZ4_VERSION_STRING}
-    LANGUAGES C)
-endif()
+message(STATUS "Creating build script for LZ4 version: ${LZ4_VERSION_STRING}")
+
+project(LZ4 VERSION ${LZ4_VERSION_STRING} LANGUAGES C)
+
 
 option(LZ4_BUILD_CLI "Build lz4 program" ON)
-option(LZ4_BUILD_LEGACY_LZ4C "Build lz4c program with legacy argument support" ON)
 
-# If LZ4 is being bundled in another project, we don't want to
-# install anything.  However, we want to let people override this, so
-# we'll use the LZ4_BUNDLED_MODE variable to let them do that; just
-# set it to OFF in your project before you add_subdirectory(lz4/contrib/cmake_unofficial).
-get_directory_property(LZ4_PARENT_DIRECTORY PARENT_DIRECTORY)
-if("${LZ4_BUNDLED_MODE}" STREQUAL "")
-  # Bundled mode hasn't been set one way or the other, set the default
-  # depending on whether or not we are the top-level project.
-  if("${LZ4_PARENT_DIRECTORY}" STREQUAL "")
-    set(LZ4_BUNDLED_MODE OFF)
-  else()
+
+# Determine if LZ4 is being built as part of another project.
+# If LZ4 is bundled in another project, we don't want to install anything.
+# Default behavior can be overridden by setting the LZ4_BUNDLED_MODE variable.
+if(NOT DEFINED LZ4_BUNDLED_MODE)
+  get_directory_property(LZ4_IS_SUBPROJECT PARENT_DIRECTORY)
+  if(LZ4_IS_SUBPROJECT)
     set(LZ4_BUNDLED_MODE ON)
+  else()
+    set(LZ4_BUNDLED_MODE OFF)
   endif()
 endif()
 mark_as_advanced(LZ4_BUNDLED_MODE)
@@ -80,19 +75,11 @@
 include_directories("${LZ4_LIB_SOURCE_DIR}")
 
 # CLI sources
-set(LZ4_SOURCES
-  "${LZ4_LIB_SOURCE_DIR}/lz4.c"
-  "${LZ4_LIB_SOURCE_DIR}/lz4hc.c"
-  "${LZ4_LIB_SOURCE_DIR}/lz4.h"
-  "${LZ4_LIB_SOURCE_DIR}/lz4hc.h"
-  "${LZ4_LIB_SOURCE_DIR}/lz4frame.c"
-  "${LZ4_LIB_SOURCE_DIR}/lz4frame.h"
-  "${LZ4_LIB_SOURCE_DIR}/xxhash.c")
-set(LZ4_CLI_SOURCES
-  "${LZ4_PROG_SOURCE_DIR}/bench.c"
-  "${LZ4_PROG_SOURCE_DIR}/lz4cli.c"
-  "${LZ4_PROG_SOURCE_DIR}/lz4io.c"
-  "${LZ4_PROG_SOURCE_DIR}/datagen.c")
+file(GLOB LZ4_SOURCES
+     "${LZ4_LIB_SOURCE_DIR}/*.c")
+file(GLOB LZ4_CLI_SOURCES
+     "${LZ4_PROG_SOURCE_DIR}/*.c")
+list(APPEND LZ4_CLI_SOURCES ${LZ4_SOURCES}) # LZ4_CLI always use liblz4 sources directly.
 
 # Whether to use position independent code for the static library.  If
 # we're building a shared library this is ignored and PIC is always
@@ -100,6 +87,7 @@
 option(LZ4_POSITION_INDEPENDENT_LIB "Use position independent code for static library (if applicable)" ON)
 
 # liblz4
+include(GNUInstallDirs)
 set(LZ4_LIBRARIES_BUILT)
 if(BUILD_SHARED_LIBS)
   add_library(lz4_shared SHARED ${LZ4_SOURCES})
@@ -130,11 +118,23 @@
     POSITION_INDEPENDENT_CODE ${LZ4_POSITION_INDEPENDENT_LIB})
   list(APPEND LZ4_LIBRARIES_BUILT lz4_static)
 endif()
-
-if(BUILD_STATIC_LIBS)
-  set(LZ4_LINK_LIBRARY lz4_static)
+# Add unified target.
+add_library(lz4 INTERFACE)
+list(APPEND LZ4_LIBRARIES_BUILT lz4)
+if(BUILD_SHARED_LIBS)
+  target_link_libraries(lz4 INTERFACE lz4_shared)
 else()
-  list(APPEND LZ4_CLI_SOURCES ${LZ4_SOURCES})
+  target_link_libraries(lz4 INTERFACE lz4_static)
+endif()
+
+# xxhash namespace
+if(BUILD_SHARED_LIBS)
+  target_compile_definitions(lz4_shared PRIVATE
+    XXH_NAMESPACE=LZ4_)
+endif()
+if(BUILD_STATIC_LIBS)
+  target_compile_definitions(lz4_static PRIVATE
+    XXH_NAMESPACE=LZ4_)
 endif()
 
 # lz4
@@ -142,55 +142,44 @@
   set(LZ4_PROGRAMS_BUILT lz4cli)
   add_executable(lz4cli ${LZ4_CLI_SOURCES})
   set_target_properties(lz4cli PROPERTIES OUTPUT_NAME lz4)
-  if (BUILD_STATIC_LIBS)
-    target_link_libraries(lz4cli ${LZ4_LINK_LIBRARY})
-  endif()
-endif()
-
-# lz4c
-if (LZ4_BUILD_LEGACY_LZ4C)
-  list(APPEND LZ4_PROGRAMS_BUILT lz4c)
-  add_executable(lz4c ${LZ4_CLI_SOURCES})
-  set_target_properties(lz4c PROPERTIES COMPILE_DEFINITIONS "ENABLE_LZ4C_LEGACY_OPTIONS")
-  if (BUILD_STATIC_LIBS)
-    target_link_libraries(lz4c ${LZ4_LINK_LIBRARY})
-  endif()
 endif()
 
 # Extra warning flags
-include (CheckCCompilerFlag)
-foreach (flag
-    # GCC-style
-    -Wall
-    -Wextra
-    -Wundef
-    -Wcast-qual
-    -Wcast-align
-    -Wshadow
-    -Wswitch-enum
-    -Wdeclaration-after-statement
-    -Wstrict-prototypes
-    -Wpointer-arith
+if(MSVC)
+  set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /W4")
+else()
+  include (CheckCCompilerFlag)
+  foreach (flag
+      # GCC-style
+      -pedantic-errors
+      -Wall
+      -Wextra
+      -Wundef
+      -Wcast-qual
+      -Wcast-align
+      -Wshadow
+      -Wswitch-enum
+      -Wdeclaration-after-statement
+      -Wstrict-prototypes
+      -Wpointer-arith)
 
-    # MSVC-style
-    /W4)
-  # Because https://gcc.gnu.org/wiki/FAQ#wnowarning
-  string(REGEX REPLACE "\\-Wno\\-(.+)" "-W\\1" flag_to_test "${flag}")
-  string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" test_name "CFLAG_${flag_to_test}")
+    # Because https://gcc.gnu.org/wiki/FAQ#wnowarning
+    string(REGEX REPLACE "\\-Wno\\-(.+)" "-W\\1" flag_to_test "${flag}")
+    string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" test_name "CFLAG_${flag_to_test}")
 
-  check_c_compiler_flag("${ADD_COMPILER_FLAGS_PREPEND} ${flag_to_test}" ${test_name})
+    check_c_compiler_flag("${ADD_COMPILER_FLAGS_PREPEND} ${flag_to_test}" ${test_name})
 
-  if(${test_name})
-    set(CMAKE_C_FLAGS "${flag} ${CMAKE_C_FLAGS}")
-  endif()
+    if(${test_name})
+      set(CMAKE_C_FLAGS_DEBUG "${flag} ${CMAKE_C_FLAGS_DEBUG}")
+    endif()
 
-  unset(test_name)
-  unset(flag_to_test)
-endforeach (flag)
+    unset(test_name)
+    unset(flag_to_test)
+  endforeach (flag)
+endif()
+
 
 if(NOT LZ4_BUNDLED_MODE)
-  include(GNUInstallDirs)
-
   install(TARGETS ${LZ4_PROGRAMS_BUILT}
     BUNDLE	DESTINATION "${CMAKE_INSTALL_BINDIR}"
     RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
@@ -201,8 +190,9 @@
     RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
   install(FILES
     "${LZ4_LIB_SOURCE_DIR}/lz4.h"
-    "${LZ4_LIB_SOURCE_DIR}/lz4frame.h"
     "${LZ4_LIB_SOURCE_DIR}/lz4hc.h"
+    "${LZ4_LIB_SOURCE_DIR}/lz4frame.h"
+    "${LZ4_LIB_SOURCE_DIR}/lz4file.h"
     DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
   install(FILES "${LZ4_PROG_SOURCE_DIR}/lz4.1"
     DESTINATION "${CMAKE_INSTALL_MANDIR}/man1")
@@ -233,16 +223,21 @@
       ${CMAKE_CURRENT_BINARY_DIR}/lz4ConfigVersion.cmake
     DESTINATION ${LZ4_PKG_INSTALLDIR})
 
-  # install lz4cat and unlz4 symlinks on *nix
+  # Install lz4cat and unlz4 symlinks on Unix systems
   if(UNIX AND LZ4_BUILD_CLI)
-    install(CODE "
-      foreach(f lz4cat unlz4)
-        set(dest \"\$ENV{DESTDIR}${CMAKE_INSTALL_FULL_BINDIR}/\${f}\")
-        message(STATUS \"Symlinking: \${dest} -> lz4\")
-        execute_process(
-          COMMAND \"${CMAKE_COMMAND}\" -E create_symlink lz4 \"\${dest}\")
-      endforeach()
-    ")
+    foreach(cli_tool IN ITEMS lz4cat unlz4)
+      # Create a custom target for the symlink creation
+      add_custom_target("create_${cli_tool}_symlink" ALL
+        COMMAND ${CMAKE_COMMAND} -E create_symlink
+          $<TARGET_FILE_NAME:lz4cli> ${cli_tool}
+        COMMENT "Creating symlink for ${cli_tool}"
+        VERBATIM)
+
+      # Install the symlink into the binary installation directory
+      install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${cli_tool}"
+        DESTINATION ${CMAKE_INSTALL_BINDIR}
+        RENAME ${cli_tool})
+    endforeach()
 
     # create manpage aliases
     foreach(f lz4cat unlz4)
diff --git a/contrib/meson/meson/GetLz4LibraryVersion.py b/build/meson/GetLz4LibraryVersion.py
similarity index 87%
rename from contrib/meson/meson/GetLz4LibraryVersion.py
rename to build/meson/GetLz4LibraryVersion.py
index d8abfcb..831fc53 100644
--- a/contrib/meson/meson/GetLz4LibraryVersion.py
+++ b/build/meson/GetLz4LibraryVersion.py
@@ -15,9 +15,9 @@
   with open(filepath) as fd:
     version_file_data = fd.read()
 
-  patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$
-#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$
-#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$
+  patterns = r"""\s*#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$
+\s*#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$
+\s*#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$
 """
   regex = re.compile(patterns, re.MULTILINE)
   version_match = regex.search(version_file_data)
diff --git a/contrib/meson/README.md b/build/meson/README.md
similarity index 100%
rename from contrib/meson/README.md
rename to build/meson/README.md
diff --git a/contrib/meson/meson.build b/build/meson/meson.build
similarity index 82%
rename from contrib/meson/meson.build
rename to build/meson/meson.build
index 39672c8..fc6408a 100644
--- a/contrib/meson/meson.build
+++ b/build/meson/meson.build
@@ -13,15 +13,19 @@
 
 project(
   'lz4',
-  ['c'],
+  'c',
   license: 'BSD-2-Clause-Patent AND GPL-2.0-or-later',
   default_options: [
     'c_std=c99',
     'buildtype=release',
     'warning_level=3'
   ],
-  version: 'DUMMY',
-  meson_version: '>=0.49.0'
+  version: run_command(
+    find_program('GetLz4LibraryVersion.py'),
+    '../../lib/lz4.h',
+    check: true
+  ).stdout().strip(),
+  meson_version: '>=0.58.0'
 )
 
 subdir('meson')
diff --git a/contrib/meson/meson/contrib/gen_manual/meson.build b/build/meson/meson/contrib/gen_manual/meson.build
similarity index 94%
rename from contrib/meson/meson/contrib/gen_manual/meson.build
rename to build/meson/meson/contrib/gen_manual/meson.build
index 84a95a9..c4349aa 100644
--- a/contrib/meson/meson/contrib/gen_manual/meson.build
+++ b/build/meson/meson/contrib/gen_manual/meson.build
@@ -10,7 +10,7 @@
 
 lz4_source_root = '../../../../..'
 
-add_languages('cpp')
+add_languages('cpp', native: true)
 
 sources = files(
   lz4_source_root / 'contrib/gen_manual/gen_manual.cpp'
@@ -33,7 +33,7 @@
     output: '@0@_manual.html'.format(mp),
     command: [
       gen_manual,
-      lz4_version,
+      meson.project_version(),
       '@INPUT@',
       '@OUTPUT@',
     ],
diff --git a/contrib/meson/meson/contrib/meson.build b/build/meson/meson/contrib/meson.build
similarity index 100%
rename from contrib/meson/meson/contrib/meson.build
rename to build/meson/meson/contrib/meson.build
diff --git a/contrib/meson/meson/examples/meson.build b/build/meson/meson/examples/meson.build
similarity index 70%
rename from contrib/meson/meson/examples/meson.build
rename to build/meson/meson/examples/meson.build
index 65f54ca..dd26334 100644
--- a/contrib/meson/meson/examples/meson.build
+++ b/build/meson/meson/examples/meson.build
@@ -11,15 +11,15 @@
 lz4_source_root = '../../../..'
 
 examples = {
-  'printVersion': 'printVersion.c',
-  'doubleBuffer': 'blockStreaming_doubleBuffer.c',
+  'print_version': 'print_version.c',
+  'blockStreaming_doubleBuffer': 'blockStreaming_doubleBuffer.c',
   'dictionaryRandomAccess': 'dictionaryRandomAccess.c',
-  'ringBuffer': 'blockStreaming_ringBuffer.c',
-  'ringBufferHC': 'HCStreaming_ringBuffer.c',
-  'lineCompress': 'blockStreaming_lineByLine.c',
+  'blockStreaming_ringBuffer': 'blockStreaming_ringBuffer.c',
+  'streamingHC_ringBuffer': 'streamingHC_ringBuffer.c',
+  'blockStreaming_lineByLine': 'blockStreaming_lineByLine.c',
   'frameCompress': 'frameCompress.c',
-  'compressFunctions': 'compress_functions.c',
-  'simpleBuffer': 'simple_buffer.c',
+  'bench_functions': 'bench_functions.c',
+  'simple_buffer': 'simple_buffer.c',
 }
 
 foreach e, src : examples
diff --git a/contrib/meson/meson/lib/meson.build b/build/meson/meson/lib/meson.build
similarity index 69%
rename from contrib/meson/meson/lib/meson.build
rename to build/meson/meson/lib/meson.build
index 469cd09..4acf614 100644
--- a/contrib/meson/meson/lib/meson.build
+++ b/build/meson/meson/lib/meson.build
@@ -17,41 +17,49 @@
   lz4_source_root / 'lib/xxhash.c'
 )
 
+if get_option('unstable')
+  sources += files(lz4_source_root / 'lib/lz4file.c')
+endif
+
 c_args = []
 
 if host_machine.system() == 'windows' and get_option('default_library') != 'static'
   c_args += '-DLZ4_DLL_EXPORT=1'
 endif
 
-if get_option('unstable')
-  compile_args += '-DLZ4_STATIC_LINKING_ONLY'
-  if get_option('default_library') != 'static'
-    c_args += '-DLZ4_PUBLISH_STATIC_FUNCTIONS'
-  endif
-endif
-
 liblz4 = library(
   'lz4',
   sources,
+  c_args: c_args,
   install: true,
-  version: lz4_version,
+  version: meson.project_version(),
   gnu_symbol_visibility: 'hidden'
 )
 
 liblz4_dep = declare_dependency(
   link_with: liblz4,
+  compile_args: compile_args,
   include_directories: include_directories(lz4_source_root / 'lib')
 )
 
-if get_option('tests') or get_option('programs') or get_option('examples')
-  liblz4_internal = static_library(
-    'lz4-internal',
-    objects: liblz4.extract_all_objects(recursive: true),
-    gnu_symbol_visibility: 'hidden'
-  )
+meson.override_dependency('liblz4', liblz4_dep)
+
+if get_option('tests') or get_option('programs') or get_option('examples') or get_option('ossfuzz')
+  if get_option('default_library') == 'shared'
+    liblz4_internal = static_library(
+      'lz4-internal',
+      objects: liblz4.extract_all_objects(recursive: true),
+      gnu_symbol_visibility: 'hidden'
+    )
+  elif get_option('default_library') == 'static'
+    liblz4_internal = liblz4
+  elif get_option('default_library') == 'both'
+    liblz4_internal = liblz4.get_static_lib()
+  endif
 
   liblz4_internal_dep = declare_dependency(
     link_with: liblz4_internal,
+    compile_args: compile_args,
     include_directories: include_directories(lz4_source_root / 'lib')
   )
 endif
@@ -61,7 +69,7 @@
   name: 'lz4',
   filebase: 'liblz4',
   description: 'extremely fast lossless compression algorithm library',
-  version: lz4_version,
+  version: meson.project_version(),
   url: 'http://www.lz4.org/'
 )
 
@@ -73,4 +81,7 @@
 
 if get_option('default_library') != 'shared'
   install_headers(lz4_source_root / 'lib/lz4frame_static.h')
+  if get_option('unstable')
+    install_headers(lz4_source_root / 'lib/lz4file.h')
+  endif
 endif
diff --git a/build/meson/meson/meson.build b/build/meson/meson/meson.build
new file mode 100644
index 0000000..90337bb
--- /dev/null
+++ b/build/meson/meson/meson.build
@@ -0,0 +1,135 @@
+# #############################################################################
+# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
+# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
+# All rights reserved.
+#
+# This source code is licensed under both the BSD-style license (found in the
+# LICENSE file in the root directory of this source tree) and the GPLv2 (found
+# in the COPYING file in the root directory of this source tree).
+# #############################################################################
+
+cc = meson.get_compiler('c')
+
+fs = import('fs')
+pkgconfig = import('pkgconfig')
+
+lz4_source_root = '../../..'
+
+add_project_arguments('-DXXH_NAMESPACE=LZ4_', language: 'c')
+
+if get_option('debug')
+  add_project_arguments(cc.get_supported_arguments(
+      '-Wcast-qual',
+      '-Wcast-align',
+      '-Wshadow',
+      '-Wswitch-enum',
+      '-Wdeclaration-after-statement',
+      '-Wstrict-prototypes',
+      '-Wundef',
+      '-Wpointer-arith',
+      '-Wstrict-aliasing=1',
+      '-DLZ4_DEBUG=@0@'.format(get_option('debug-level'))
+    ),
+    language: 'c'
+  )
+endif
+
+compile_args = []
+
+if not get_option('align-test')
+  add_project_arguments('-DLZ4_ALIGN_TEST=0', language: 'c')
+endif
+
+if get_option('disable-memory-allocation')
+  if get_option('default_library') != 'static'
+    error('Memory allocation can only be disabled in static builds')
+  endif
+
+  add_project_arguments('-DLZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION')
+  compile_args += '-DLZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION'
+endif
+
+add_project_arguments(
+  '-DLZ4_DISTANCE_MAX=@0@'.format(get_option('distance-max')),
+  language: 'c'
+)
+compile_args += '-DLZ4_DISTANCE_MAX=@0@'.format(get_option('distance-max'))
+
+if not get_option('fast-dec-loop').auto()
+  add_project_arguments(
+    '-DLZ4_FAST_DEC_LOOP=@0@'.format(
+      get_option('fast-dec-loop').enabled() ? 1 : 0
+    ),
+    language: 'c'
+  )
+endif
+
+if get_option('force-sw-bitcount')
+  add_project_arguments('-DLZ4_FORCE_SW_BITCOUNT', language: 'c')
+endif
+
+if get_option('freestanding')
+  add_project_arguments('-DLZ4_FREESTANDING=1', language: 'c')
+  compile_args += '-DLZ4_FREESTANDING=1'
+endif
+
+if get_option('memory-usage') > 0
+  add_project_arguments(
+    '-DLZ4_MEMORY_USAGE=@0@'.format(get_option('memory-usage')),
+    language: 'c'
+  )
+  compile_args += '-DLZ4_MEMORY_USAGE=@0@'.format(get_option('memory-usage'))
+endif
+
+if get_option('endianness-independent-output')
+  if get_option('default_library') != 'static'
+    error('Endianness-independent output can only be enabled in static builds')
+  endif
+
+  add_project_arguments('-DLZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT')
+  compile_args += '-DLZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT'
+endif
+
+if get_option('unstable')
+  add_project_arguments('-DLZ4_STATIC_LINKING_ONLY', language: 'c')
+  compile_args += '-DLZ4_STATIC_LINKING_ONLY'
+  if get_option('default_library') != 'static'
+    add_project_arguments('-DLZ4_PUBLISH_STATIC_FUNCTIONS', language: 'c')
+    compile_args += '-DLZ4_PUBLISH_STATIC_FUNCTIONS'
+
+    add_project_arguments('-DLZ4F_PUBLISH_STATIC_FUNCTIONS', language: 'c')
+    compile_args += '-DLZ4F_PUBLISH_STATIC_FUNCTIONS'
+  endif
+endif
+
+if get_option('user-memory-functions')
+  add_project_arguments('-DLZ4_USER_MEMORY_FUNCTIONS', language: 'c')
+endif
+
+run_env = environment()
+
+subdir('lib')
+
+if get_option('programs')
+  subdir('programs')
+else
+  lz4 = disabler()
+  lz4cat = disabler()
+  unlz4 = disabler()
+endif
+
+if get_option('tests')
+  subdir('tests')
+endif
+
+if get_option('contrib')
+  subdir('contrib')
+endif
+
+if get_option('examples')
+  subdir('examples')
+endif
+
+if get_option('ossfuzz')
+  subdir('ossfuzz')
+endif
diff --git a/build/meson/meson/ossfuzz/meson.build b/build/meson/meson/ossfuzz/meson.build
new file mode 100644
index 0000000..9945d8c
--- /dev/null
+++ b/build/meson/meson/ossfuzz/meson.build
@@ -0,0 +1,35 @@
+fuzzers = [
+  'compress_frame_fuzzer',
+  'compress_fuzzer',
+  'compress_hc_fuzzer',
+  'decompress_frame_fuzzer',
+  'decompress_fuzzer',
+  'round_trip_frame_uncompressed_fuzzer',
+  'round_trip_fuzzer',
+  'round_trip_hc_fuzzer',
+  'round_trip_stream_fuzzer'
+]
+
+c_args = cc.get_supported_arguments(
+  '-Wno-unused-function',
+  '-Wno-sign-compare',
+  '-Wno-declaration-after-statement'
+)
+
+foreach f : fuzzers
+  lib = static_library(
+    f,
+    lz4_source_root / 'ossfuzz/@0@.c'.format(f),
+    lz4_source_root / 'ossfuzz/lz4_helpers.c',
+    lz4_source_root / 'ossfuzz/fuzz_data_producer.c',
+    c_args: c_args,
+    dependencies: [liblz4_internal_dep]
+  )
+
+  executable(
+    f,
+    lz4_source_root / 'ossfuzz/standaloneengine.c',
+    link_with: lib,
+    dependencies: [liblz4_internal_dep]
+  )
+endforeach
diff --git a/build/meson/meson/programs/meson.build b/build/meson/meson/programs/meson.build
new file mode 100644
index 0000000..16f802b
--- /dev/null
+++ b/build/meson/meson/programs/meson.build
@@ -0,0 +1,91 @@
+# #############################################################################
+# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
+# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
+# All rights reserved.
+#
+# This source code is licensed under both the BSD-style license (found in the
+# LICENSE file in the root directory of this source tree) and the GPLv2 (found
+# in the COPYING file in the root directory of this source tree).
+# #############################################################################
+
+lz4_source_root = '../../../..'
+
+# note:
+# it would be preferable to use some kind of glob or wildcard expansion here...
+sources = files(
+  lz4_source_root / 'programs/bench.c',
+  lz4_source_root / 'programs/lorem.c',
+  lz4_source_root / 'programs/lz4cli.c',
+  lz4_source_root / 'programs/lz4io.c',
+  lz4_source_root / 'programs/util.c',
+  lz4_source_root / 'programs/threadpool.c',
+  lz4_source_root / 'programs/timefn.c',
+)
+
+# Initialize an empty list for extra dependencies
+extra_deps = []
+
+if get_option('enable_multithread')
+  pthread_dep = dependency('threads', required : true)
+  extra_deps += [pthread_dep]
+  multithread_args = ['-DLZ4IO_MULTITHREAD']
+else
+  multithread_args = []
+endif
+
+lz4 = executable(
+  'lz4',
+  sources,
+  include_directories: include_directories(lz4_source_root / 'programs'),
+  dependencies: [liblz4_internal_dep] + extra_deps,
+  c_args: multithread_args,
+  export_dynamic: get_option('debug') and host_machine.system() == 'windows',
+  install: true
+)
+
+lz4cat = custom_target(
+  'lz4cat',
+  input: lz4,
+  output: 'lz4cat',
+  command: [
+    'ln',
+    '--symbolic',
+    '--force',
+    fs.name(lz4.full_path()),
+    '@OUTPUT@'
+  ]
+)
+
+unlz4 = custom_target(
+  'unlz4',
+  input: lz4,
+  output: 'unlz4',
+  command: [
+    'ln',
+    '--symbolic',
+    '--force',
+    fs.name(lz4.full_path()),
+    '@OUTPUT@'
+  ]
+)
+
+meson.override_find_program('lz4', lz4)
+
+run_env.prepend('PATH', meson.current_build_dir())
+
+install_man(lz4_source_root / 'programs/lz4.1')
+
+if meson.version().version_compare('>=0.61.0')
+  foreach alias : ['lz4c', 'lz4cat', 'unlz4']
+    install_symlink(
+      alias,
+      install_dir: get_option('bindir'),
+      pointing_to: 'lz4'
+    )
+    install_symlink(
+      '@0@.1'.format(alias),
+      install_dir: get_option('mandir') / 'man1',
+      pointing_to: 'lz4.1'
+    )
+  endforeach
+endif
diff --git a/build/meson/meson/tests/meson.build b/build/meson/meson/tests/meson.build
new file mode 100644
index 0000000..4cf86a6
--- /dev/null
+++ b/build/meson/meson/tests/meson.build
@@ -0,0 +1,162 @@
+# #############################################################################
+# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
+# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
+# All rights reserved.
+#
+# This source code is licensed under both the BSD-style license (found in the
+# LICENSE file in the root directory of this source tree) and the GPLv2 (found
+# in the COPYING file in the root directory of this source tree).
+# #############################################################################
+
+lz4_source_root = '../../../..'
+
+fuzzer_time = 90
+test_exes = {
+  'abiTest': {
+    'sources': files(lz4_source_root / 'tests/abiTest.c'),
+    'test': false,
+  },
+  'checkFrame': {
+    'sources': files(lz4_source_root / 'tests/checkFrame.c'),
+    'include_directories': include_directories(lz4_source_root / 'programs'),
+  },
+  'checkTag': {
+    'sources': files(lz4_source_root / 'tests/checkTag.c'),
+    'test': false,
+  },
+  'datagen': {
+    'sources': files(
+        lz4_source_root / 'programs/lorem.c',
+        lz4_source_root / 'tests/datagencli.c',
+        lz4_source_root / 'tests/datagen.c',
+        lz4_source_root / 'tests/loremOut.c',
+        ),
+    'include_directories': include_directories(lz4_source_root / 'programs'),
+  },
+  'decompress-partial-usingDict.c': {
+    'sources': files(lz4_source_root / 'tests/decompress-partial-usingDict.c'),
+  },
+  'decompress-partial.c': {
+    'sources': files(lz4_source_root / 'tests/decompress-partial.c'),
+  },
+  'frametest': {
+    'sources': files(lz4_source_root / 'tests/frametest.c'),
+    'include_directories': include_directories(lz4_source_root / 'programs'),
+    'args': ['-v', '-T@0@s'.format(fuzzer_time)],
+    'test': false,
+  },
+  'freestanding': {
+    'sources': files(lz4_source_root / 'tests/freestanding.c'),
+    'c_args': ['-ffreestanding', '-Wno-unused-parameter', '-Wno-declaration-after-statement'],
+    'link_args': ['-nostdlib'],
+    'build': cc.get_id() in ['gcc', 'clang'] and
+      host_machine.system() == 'linux' and host_machine.cpu_family() == 'x86_64',
+    'override_options': ['optimization=1'],
+  },
+  'fullbench': {
+    'sources': files(lz4_source_root / 'tests/fullbench.c'),
+    'include_directories': include_directories(lz4_source_root / 'programs'),
+    'args': ['--no-prompt', '-i1', files(lz4_source_root / 'tests/COPYING')],
+    'test': false,
+  },
+  'fuzzer': {
+    'sources': files(lz4_source_root / 'tests/fuzzer.c'),
+    'include_directories': include_directories(lz4_source_root / 'programs'),
+    'args': ['-T@0@s'.format(fuzzer_time)],
+    'test': false,
+  },
+  'roundTripTest': {
+    'sources': files(lz4_source_root / 'tests/roundTripTest.c'),
+    'test': false,
+  },
+}
+
+targets = {}
+
+foreach e, attrs : test_exes
+  if not attrs.get('build', true)
+    targets += {e: disabler()}
+    continue
+  endif
+
+  t = executable(
+    e,
+    attrs.get('sources'),
+    c_args: attrs.get('c_args', []),
+    link_args: attrs.get('link_args', []),
+    objects: attrs.get('objects', []),
+    dependencies: [liblz4_internal_dep],
+    include_directories: attrs.get('include_directories', []),
+    install: false,
+    override_options: attrs.get('override_options', [])
+  )
+
+  targets += {e: t}
+
+  if not attrs.get('test', true)
+    continue
+  endif
+
+  test(
+    e,
+    t,
+    args: attrs.get('params', []),
+    timeout: 120
+  )
+endforeach
+
+fs = import('fs')
+
+run_env.prepend('PATH', meson.current_build_dir())
+
+test_scripts = {
+  'lz4-basic': {
+    'depends': [lz4, lz4cat, unlz4, targets['datagen']],
+  },
+  'lz4-dict': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-contentSize': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-fast-hugefile': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-frame-concatenation': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-multiple': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-multiple-legacy': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-opt-parser': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-skippable': {
+    'depends': [lz4],
+  },
+  'lz4-sparse': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4-testmode': {
+    'depends': [lz4, targets['datagen']],
+  },
+  'lz4hc-hugefile': {
+    'depends': [lz4, targets['datagen']],
+  },
+}
+
+foreach s, attrs : test_scripts
+  script = find_program(lz4_source_root / 'tests/test-@0@.sh'.format(s))
+
+  test(
+    '@0@'.format(s),
+    script,
+    depends: attrs.get('depends', []),
+    workdir: fs.parent(script.full_path()),
+    env: run_env,
+    timeout: 360
+  )
+endforeach
diff --git a/build/meson/meson_options.txt b/build/meson/meson_options.txt
new file mode 100644
index 0000000..d9c30d6
--- /dev/null
+++ b/build/meson/meson_options.txt
@@ -0,0 +1,44 @@
+# #############################################################################
+# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
+# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
+# All rights reserved.
+#
+# This source code is licensed under both the BSD-style license (found in the
+# LICENSE file in the root directory of this source tree) and the GPLv2 (found
+# in the COPYING file in the root directory of this source tree).
+# #############################################################################
+
+option('enable_multithread', type: 'boolean', value: true,
+  description: 'Enable multi-threading support')
+option('align-test', type: 'boolean', value: true,
+  description: 'See LZ4_ALIGN_TEST')
+option('contrib', type: 'boolean', value: false,
+  description: 'Enable contrib')
+option('debug-level', type: 'integer', min: 0, max: 7, value: 1,
+  description: 'Enable run-time debug. See lib/lz4hc.c')
+option('disable-memory-allocation', type: 'boolean', value: false,
+  description: 'See LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION. Static builds only')
+option('distance-max', type: 'integer', min: 0, max: 65535, value: 65535,
+  description: 'See LZ4_DISTANCE_MAX')
+option('endianness-independent-output', type: 'boolean', value: false,
+  description: 'See LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT. Static builds only')
+option('examples', type: 'boolean', value: false,
+  description: 'Enable examples')
+option('fast-dec-loop', type: 'feature', value: 'auto',
+  description: 'See LZ4_FAST_DEC_LOOP')
+option('force-sw-bitcount', type: 'boolean', value: false,
+  description: 'See LZ4_FORCE_SW_BITCOUNT')
+option('freestanding', type: 'boolean', value: false,
+  description: 'See LZ4_FREESTANDING')
+option('memory-usage', type: 'integer', min: 0, max: 20, value: 0,
+  description: 'See LZ4_MEMORY_USAGE. 0 means use the LZ4 default')
+option('ossfuzz', type: 'boolean', value: true,
+  description: 'Enable ossfuzz')
+option('programs', type: 'boolean', value: false,
+  description: 'Enable programs')
+option('tests', type: 'boolean', value: false,
+  description: 'Enable tests')
+option('unstable', type: 'boolean', value: false,
+  description: 'Expose unstable interfaces')
+option('user-memory-functions', type: 'boolean', value: false,
+  description: 'See LZ4_USER_MEMORY_FUNCTIONS')
diff --git a/build/visual/README.md b/build/visual/README.md
new file mode 100644
index 0000000..e96c42a
--- /dev/null
+++ b/build/visual/README.md
@@ -0,0 +1,5 @@
+These scripts will generate Visual Studio Solutions for a selected set of supported versions of MS Visual.
+
+For these scripts to work, both `cmake` and the relevant Visual Studio version must be locally installed on the system where the script is run.
+
+If `cmake` is installed into a non-standard directory, or user wants to test a specific version of `cmake`, the target `cmake` directory can be provided via the environment variable `CMAKE_PATH`.
diff --git a/build/visual/generate_solution.cmd b/build/visual/generate_solution.cmd
new file mode 100644
index 0000000..644d812
--- /dev/null
+++ b/build/visual/generate_solution.cmd
@@ -0,0 +1,55 @@
+:: Requires 1 parameter == GENERATOR
+@echo off
+setlocal
+
+:: Set path
+set "BUILD_BASE_DIR=%~dp0"  :: Use the directory where the script is located
+set "CMAKELIST_DIR=..\..\cmake"
+
+if "%~1"=="" (
+    echo No generator specified as first parameter
+    exit /b 1
+)
+set "GENERATOR=%~1"
+
+:: Check if a user-defined CMAKE_PATH is set and prioritize it
+if defined CMAKE_PATH (
+    set "CMAKE_EXECUTABLE=%CMAKE_PATH%\cmake.exe"
+    echo Using user-defined cmake at %CMAKE_PATH%
+) else (
+    :: Attempt to find cmake in the system PATH
+    where cmake >nul 2>&1
+    if %ERRORLEVEL% neq 0 (
+        :: Use the default standard cmake installation directory if not found in PATH
+        set "CMAKE_PATH=C:\Program Files\CMake\bin"
+        echo CMake not in system PATH => using default CMAKE_PATH=%CMAKE_PATH%
+        set "CMAKE_EXECUTABLE=%CMAKE_PATH%\cmake.exe"
+    ) else (
+        set "CMAKE_EXECUTABLE=cmake"
+        echo CMake found in system PATH.
+    )
+)
+
+:: Set the build directory to a subdirectory named after the generator
+set "BUILD_DIR=%BUILD_BASE_DIR%\%GENERATOR%"
+
+:: Create the build directory if it doesn't exist
+if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
+
+:: Run CMake to configure the project and generate the solution
+pushd "%BUILD_DIR%"
+"%CMAKE_EXECUTABLE%" -G "%GENERATOR%" "%CMAKELIST_DIR%"
+if %ERRORLEVEL% neq 0 goto :error
+
+:: If successful, end script
+echo Build configuration successful for %GENERATOR%.
+goto :end
+
+:error
+echo Failed to configure build for %GENERATOR%.
+exit /b 1
+
+:end
+popd
+endlocal
+@echo on
diff --git a/build/visual/generate_vs2015.cmd b/build/visual/generate_vs2015.cmd
new file mode 100644
index 0000000..9b64a4f
--- /dev/null
+++ b/build/visual/generate_vs2015.cmd
@@ -0,0 +1,3 @@
+@echo off
+:: Call the central script with the specific generator for VS2015
+call generate_solution.cmd "Visual Studio 14 2015"
diff --git a/build/visual/generate_vs2017.cmd b/build/visual/generate_vs2017.cmd
new file mode 100644
index 0000000..d5ab8fc
--- /dev/null
+++ b/build/visual/generate_vs2017.cmd
@@ -0,0 +1,3 @@
+@echo off
+:: Call the central script with the specific generator for VS2017
+call generate_solution.cmd "Visual Studio 15 2017"
diff --git a/build/visual/generate_vs2019.cmd b/build/visual/generate_vs2019.cmd
new file mode 100644
index 0000000..653fc6e
--- /dev/null
+++ b/build/visual/generate_vs2019.cmd
@@ -0,0 +1,3 @@
+@echo off
+:: Call the central script with the specific generator for VS2019
+call generate_solution.cmd "Visual Studio 16 2019"
diff --git a/build/visual/generate_vs2022.cmd b/build/visual/generate_vs2022.cmd
new file mode 100644
index 0000000..a48f744
--- /dev/null
+++ b/build/visual/generate_vs2022.cmd
@@ -0,0 +1,3 @@
+@echo off
+:: Call the central script with the specific generator for VS2022
+call generate_solution.cmd "Visual Studio 17 2022"
diff --git a/contrib/djgpp/Makefile b/contrib/djgpp/Makefile
index 8cd3580..f6388b4 100644
--- a/contrib/djgpp/Makefile
+++ b/contrib/djgpp/Makefile
@@ -7,9 +7,9 @@
 # Version numbers
 VERSION ?= 129
 RELEASE ?= r$(VERSION)
-LIBVER_MAJOR=$(shell sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
-LIBVER_MINOR=$(shell sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
-LIBVER_PATCH=$(shell sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
+LIBVER_MAJOR=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
+LIBVER_MINOR=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
+LIBVER_PATCH=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h)
 LIBVER=$(LIBVER_MAJOR).$(LIBVER_MINOR).$(LIBVER_PATCH)
 
 ######################################################################
@@ -19,7 +19,7 @@
 AR = $(CROSS)-ar
 LD = $(CROSS)-gcc
 
-CFLAGS ?= -O3 -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes -pedantic -DLZ4_VERSION=\"$(RELEASE)\"
+CFLAGS ?= -O3 -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes -Wpedantic -DLZ4_VERSION=\"$(RELEASE)\"
 LDFLAGS ?= -s
 SRC = programs/bench.c programs/lz4io.c programs/lz4cli.c
 OBJ = $(SRC:.c=.o)
diff --git a/contrib/gen_manual/Makefile b/contrib/gen_manual/Makefile
index 262c80d..49daad4 100644
--- a/contrib/gen_manual/Makefile
+++ b/contrib/gen_manual/Makefile
@@ -39,9 +39,9 @@
 LZ4MANUAL = ../../doc/lz4_manual.html
 LZ4FAPI = ../../lib/lz4frame.h
 LZ4FMANUAL = ../../doc/lz4frame_manual.html
-LIBVER_MAJOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
-LIBVER_MINOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
-LIBVER_PATCH_SCRIPT:=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
+LIBVER_MAJOR_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
+LIBVER_MINOR_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
+LIBVER_PATCH_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)`
 LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
 LZ4VER := $(shell echo $(LIBVER_SCRIPT))
 
diff --git a/contrib/gen_manual/gen-lz4-manual.sh b/contrib/gen_manual/gen-lz4-manual.sh
index 73a7214..7bbfe18 100644
--- a/contrib/gen_manual/gen-lz4-manual.sh
+++ b/contrib/gen_manual/gen-lz4-manual.sh
@@ -1,8 +1,8 @@
 #!/bin/sh
 
-LIBVER_MAJOR_SCRIPT=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
-LIBVER_MINOR_SCRIPT=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
-LIBVER_PATCH_SCRIPT=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
+LIBVER_MAJOR_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
+LIBVER_MINOR_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
+LIBVER_PATCH_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h`
 LIBVER_SCRIPT=$LIBVER_MAJOR_SCRIPT.$LIBVER_MINOR_SCRIPT.$LIBVER_PATCH_SCRIPT
 
 echo LZ4_VERSION=$LIBVER_SCRIPT
diff --git a/contrib/meson/meson/meson.build b/contrib/meson/meson/meson.build
deleted file mode 100644
index 9e8b8c6..0000000
--- a/contrib/meson/meson/meson.build
+++ /dev/null
@@ -1,67 +0,0 @@
-# #############################################################################
-# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
-# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
-# All rights reserved.
-#
-# This source code is licensed under both the BSD-style license (found in the
-# LICENSE file in the root directory of this source tree) and the GPLv2 (found
-# in the COPYING file in the root directory of this source tree).
-# #############################################################################
-
-cc = meson.get_compiler('c')
-
-pkgconfig = import('pkgconfig')
-
-lz4_source_root = '../../..'
-
-lz4_version = meson.project_version()
-
-lz4_h_file = lz4_source_root / 'lib/lz4.h'
-GetLz4LibraryVersion_py = find_program('GetLz4LibraryVersion.py')
-lz4_version = run_command(GetLz4LibraryVersion_py, lz4_h_file, check: true).stdout().strip()
-message('Project version is now: @0@'.format(lz4_version))
-
-add_project_arguments('-DXXH_NAMESPACE=LZ4_', language: 'c')
-
-if get_option('debug')
-  add_project_arguments(cc.get_supported_arguments([
-        '-Wcast-qual',
-        '-Wcast-align',
-        '-Wshadow',
-        '-Wswitch-enum',
-        '-Wdeclaration-after-statement',
-        '-Wstrict-prototypes',
-        '-Wundef',
-        '-Wpointer-arith',
-        '-Wstrict-aliasing=1',
-        '-DLZ4_DEBUG=@0@'.format(get_option('debug-level')),
-      ]
-    ),
-    language: 'c',
-  )
-endif
-
-if get_option('memory-usage') > 0
-  add_project_arguments(
-    '-DLZ4_MEMORY_USAGE=@0@'.format(get_option('memory-usage')),
-    language: 'c'
-  )
-endif
-
-subdir('lib')
-
-if get_option('programs')
-  subdir('programs')
-endif
-
-if get_option('tests')
-  subdir('tests')
-endif
-
-if get_option('contrib')
-  subdir('contrib')
-endif
-
-if get_option('examples')
-  subdir('examples')
-endif
diff --git a/contrib/meson/meson/programs/meson.build b/contrib/meson/meson/programs/meson.build
deleted file mode 100644
index f9d5bf1..0000000
--- a/contrib/meson/meson/programs/meson.build
+++ /dev/null
@@ -1,44 +0,0 @@
-# #############################################################################
-# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
-# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
-# All rights reserved.
-#
-# This source code is licensed under both the BSD-style license (found in the
-# LICENSE file in the root directory of this source tree) and the GPLv2 (found
-# in the COPYING file in the root directory of this source tree).
-# #############################################################################
-
-lz4_source_root = '../../../..'
-
-sources = files(
-  lz4_source_root / 'programs/bench.c',
-  lz4_source_root / 'programs/datagen.c',
-  lz4_source_root / 'programs/lz4cli.c',
-  lz4_source_root / 'programs/lz4io.c',
-)
-
-lz4 = executable(
-  'lz4',
-  sources,
-  include_directories: include_directories(lz4_source_root / 'programs'),
-  dependencies: [liblz4_internal_dep],
-  export_dynamic: get_option('debug') and host_machine.system() == 'windows',
-  install: true
-)
-
-install_man(lz4_source_root / 'programs/lz4.1')
-
-if meson.version().version_compare('>=0.61.0')
-  foreach alias : ['lz4c', 'lz4cat', 'unlz4']
-    install_symlink(
-      alias,
-      install_dir: get_option('bindir'),
-      pointing_to: 'lz4'
-    )
-    install_symlink(
-      '@0@.1'.format(alias),
-      install_dir: get_option('mandir') / 'man1',
-      pointing_to: 'lz4.1'
-    )
-  endforeach
-endif
diff --git a/contrib/meson/meson/tests/meson.build b/contrib/meson/meson/tests/meson.build
deleted file mode 100644
index 18479e4..0000000
--- a/contrib/meson/meson/tests/meson.build
+++ /dev/null
@@ -1,52 +0,0 @@
-# #############################################################################
-# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
-# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
-# All rights reserved.
-#
-# This source code is licensed under both the BSD-style license (found in the
-# LICENSE file in the root directory of this source tree) and the GPLv2 (found
-# in the COPYING file in the root directory of this source tree).
-# #############################################################################
-
-lz4_source_root = '../../../..'
-
-exes = {
-  'fullbench': {
-    'sources': files(lz4_source_root / 'tests/fullbench.c'),
-    'include_directories': include_directories(lz4_source_root / 'programs'),
-  },
-  'fuzzer': {
-    'sources': files(lz4_source_root / 'tests/fuzzer.c'),
-    'include_directories': include_directories(lz4_source_root / 'programs'),
-  },
-  'frametest': {
-    'sources': files(lz4_source_root / 'tests/frametest.c'),
-    'include_directories': include_directories(lz4_source_root / 'programs'),
-  },
-  'roundTripTest': {
-    'sources': files(lz4_source_root / 'tests/roundTripTest.c'),
-  },
-  'datagen': {
-    'sources': files(lz4_source_root / 'tests/datagencli.c'),
-    'objects': lz4.extract_objects(lz4_source_root / 'programs/datagen.c'),
-    'include_directories': include_directories(lz4_source_root / 'programs'),
-  },
-  'checkFrame': {
-    'sources': files(lz4_source_root / 'tests/checkFrame.c'),
-    'include_directories': include_directories(lz4_source_root / 'programs'),
-  },
-  'checkTag': {
-    'sources': files(lz4_source_root / 'tests/checkTag.c'),
-  },
-}
-
-foreach e, attrs : exes
-  executable(
-    e,
-    attrs.get('sources'),
-    objects: attrs.get('objects', []),
-    dependencies: [liblz4_internal_dep],
-    include_directories: attrs.get('include_directories', []),
-    install: false
-  )
-endforeach
diff --git a/contrib/meson/meson_options.txt b/contrib/meson/meson_options.txt
deleted file mode 100644
index ccb32de..0000000
--- a/contrib/meson/meson_options.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-# #############################################################################
-# Copyright (c) 2018-present        lzutao <taolzu(at)gmail.com>
-# Copyright (c) 2022-present        Tristan Partin <tristan(at)partin.io>
-# All rights reserved.
-#
-# This source code is licensed under both the BSD-style license (found in the
-# LICENSE file in the root directory of this source tree) and the GPLv2 (found
-# in the COPYING file in the root directory of this source tree).
-# #############################################################################
-
-option('debug-level', type: 'integer', min: 0, max: 7, value: 1,
-  description: 'Enable run-time debug. See lib/lz4hc.c')
-option('unstable', type: 'boolean', value: false,
-  description: 'Expose unstable interfaces')
-option('programs', type: 'boolean', value: false,
-  description: 'Enable programs build')
-option('tests', type: 'boolean', value: false,
-  description: 'Enable tests build')
-option('contrib', type: 'boolean', value: false,
-  description: 'Enable contrib build')
-option('examples', type: 'boolean', value: false,
-  description: 'Enable examples build')
-option('memory-usage', type: 'integer', min: 0, value: 0,
-  description: 'See LZ4_MEMORY_USAGE. 0 means use the LZ4 default')
diff --git a/contrib/snap/snapcraft.yaml b/contrib/snap/snapcraft.yaml
index 04ad3c4..7757a10 100644
--- a/contrib/snap/snapcraft.yaml
+++ b/contrib/snap/snapcraft.yaml
@@ -1,5 +1,5 @@
 name: lz4
-version: 1.9.3 
+version: 1.9.4 
 summary: Extremely Fast Compression algorithm 
 description: >
     LZ4 is lossless compression algorithm, providing compression
@@ -20,6 +20,7 @@
     LZ4 library is provided as open-source software using BSD 2-Clause license.
 confinement: strict
 grade: stable
+base: core20
 
 apps:
   lz4:
diff --git a/doc/lz4_Frame_format.md b/doc/lz4_Frame_format.md
index 97a2cbe..24f2734 100644
--- a/doc/lz4_Frame_format.md
+++ b/doc/lz4_Frame_format.md
@@ -16,7 +16,7 @@
 
 ### Version
 
-1.6.2 (12/08/2020)
+1.6.4 (28/12/2023)
 
 
 Introduction
@@ -61,9 +61,9 @@
 General Structure of LZ4 Frame format
 -------------------------------------
 
-| MagicNb | F. Descriptor | Block | (...) | EndMark | C. Checksum |
-|:-------:|:-------------:| ----- | ----- | ------- | ----------- |
-| 4 bytes |  3-15 bytes   |       |       | 4 bytes | 0-4 bytes   |
+| MagicNb | F. Descriptor | Data Block | (...) | EndMark | C. Checksum |
+|:-------:|:-------------:| ---------- | ----- | ------- | ----------- |
+| 4 bytes |  3-15 bytes   |            |       | 4 bytes | 0-4 bytes   |
 
 __Magic Number__
 
@@ -219,24 +219,26 @@
 
 __Dictionary ID__
 
+A dictionary is useful to compress short input sequences.
+When present, the compressor can take advantage of dictionary's content
+as a kind of “known prefix” to encode the input in a more compact manner.
+
+When the frame descriptor defines independent blocks,
+every block is initialized with the same dictionary.
+If the frame descriptor defines linked blocks,
+the dictionary is only used once, at the beginning of the frame.
+
+The compressor and the decompressor must employ exactly the same dictionary for the data to be decodable.
+
+The Dict-ID field is offered as a way to help the decoder determine
+which dictionary must be used to correctly decode the compressed frame.
 Dict-ID is only present if the associated flag is set.
 It's an unsigned 32-bits value, stored using little-endian convention.
-A dictionary is useful to compress short input sequences.
-The compressor can take advantage of the dictionary context
-to encode the input in a more compact manner.
-It works as a kind of “known prefix” which is used by
-both the compressor and the decompressor to “warm-up” reference tables.
+Within a single frame, only a single Dict-ID field can be defined.
 
-The decompressor can use Dict-ID identifier to determine
-which dictionary must be used to correctly decode data.
-The compressor and the decompressor must use exactly the same dictionary.
-It's presumed that the 32-bits dictID uniquely identifies a dictionary.
-
-Within a single frame, a single dictionary can be defined.
-When the frame descriptor defines independent blocks,
-each block will be initialized with the same dictionary.
-If the frame descriptor defines linked blocks,
-the dictionary will only be used once, at the beginning of the frame.
+Note that the Dict-ID field is optional.
+Knowledge of which dictionary to employ can also be passed off-band,
+for example, it could be implied by the context of the application.
 
 __Header Checksum__
 
@@ -269,7 +271,7 @@
 
 _Block_Size_ shall never be larger than _Block_Maximum_Size_.
 Such an outcome could potentially happen for non-compressible sources.
-In such a case, such data block must be passed using uncompressed format.
+In such a case, such data block **must** be passed using uncompressed format.
 
 A value of `0x00000000` is invalid, and signifies an _EndMark_ instead.
 Note that this is different from a value of `0x80000000` (highest bit set),
@@ -397,6 +399,10 @@
 Version changes
 ---------------
 
+1.6.4 : minor clarifications for Dictionaries
+
+1.6.3 : minor : clarify Data Block
+
 1.6.2 : clarifies specification of _EndMark_
 
 1.6.1 : introduced terms "LZ4 Frame Header" and "LZ4 Frame Footer"
@@ -427,6 +433,6 @@
 
 0.6 : settled : stream size uses 8 bytes, endian convention is little endian
 
-0.5: added copyright notice
+0.5 : added copyright notice
 
 0.4 : changed format to Google Doc compatible OpenDocument
diff --git a/doc/lz4_manual.html b/doc/lz4_manual.html
index 6fafb21..28d0930 100644
--- a/doc/lz4_manual.html
+++ b/doc/lz4_manual.html
@@ -1,16 +1,16 @@
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
-<title>1.9.4 Manual</title>
+<title>1.10.0 Manual</title>
 </head>
 <body>
-<h1>1.9.4 Manual</h1>
+<h1>1.10.0 Manual</h1>
 <hr>
 <a name="Contents"></a><h2>Contents</h2>
 <ol>
 <li><a href="#Chapter1">Introduction</a></li>
 <li><a href="#Chapter2">Version</a></li>
-<li><a href="#Chapter3">Tuning parameter</a></li>
+<li><a href="#Chapter3">Tuning memory usage</a></li>
 <li><a href="#Chapter4">Simple Functions</a></li>
 <li><a href="#Chapter5">Advanced Functions</a></li>
 <li><a href="#Chapter6">Streaming Compression Functions</a></li>
@@ -83,15 +83,16 @@
 </b></pre><BR>
 <pre><b>const char* LZ4_versionString (void);   </b>/**< library version string; useful to check dll version; requires v1.7.5+ */<b>
 </b></pre><BR>
-<a name="Chapter3"></a><h2>Tuning parameter</h2><pre></pre>
+<a name="Chapter3"></a><h2>Tuning memory usage</h2><pre></pre>
 
 <pre><b>#ifndef LZ4_MEMORY_USAGE
 # define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
 #endif
-</b><p> Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; )
- Increasing memory usage improves compression ratio, at the cost of speed.
+</b><p> Can be selected at compile time, by setting LZ4_MEMORY_USAGE.
+ Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB)
+ Increasing memory usage improves compression ratio, generally at the cost of speed.
  Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality.
- Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
+ Default value is 14, for 16KB, which nicely fits into most L1 caches.
  
 </p></pre><BR>
 
@@ -114,8 +115,9 @@
 </p></pre><BR>
 
 <pre><b>int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity);
-</b><p>  compressedSize : is the exact complete size of the compressed block.
-  dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size.
+</b><p> @compressedSize : is the exact complete size of the compressed block.
+ @dstCapacity : is the size of destination buffer (which must be already allocated),
+                presumed an upper bound of decompressed size.
  @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
            If destination buffer is not large enough, decoding will stop and output an error code (negative value).
            If the source stream is detected malformed, the function will stop decoding and return a negative result.
@@ -159,19 +161,20 @@
  
 </p></pre><BR>
 
-<pre><b>int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
+<pre><b>int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize);
 </b><p>  Reverse the logic : compresses as much data as possible from 'src' buffer
-  into already allocated buffer 'dst', of size >= 'targetDestSize'.
+  into already allocated buffer 'dst', of size >= 'dstCapacity'.
   This function either compresses the entire 'src' content into 'dst' if it's large enough,
   or fill 'dst' buffer completely with as much data as possible from 'src'.
   note: acceleration parameter is fixed to "default".
 
- *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
+ *srcSizePtr : in+out parameter. Initially contains size of input.
+               Will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
                New value is necessarily <= input value.
- @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
+ @return : Nb bytes written into 'dst' (necessarily <= dstCapacity)
            or 0 if compression fails.
 
- Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):
+ Note : from v1.8.2 to v1.9.1, this function had a bug (fixed in v1.9.2+):
         the produced compressed content could, in specific circumstances,
         require to be decompressed into a destination buffer larger
         by at least 1 byte than the content to decompress.
@@ -222,6 +225,24 @@
 
 <a name="Chapter6"></a><h2>Streaming Compression Functions</h2><pre></pre>
 
+<pre><b>#if !defined(RC_INVOKED) </b>/* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */<b>
+#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
+LZ4_stream_t* LZ4_createStream(void);
+int           LZ4_freeStream (LZ4_stream_t* streamPtr);
+#endif </b>/* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */<b>
+#endif
+</b><p>
+ - RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio).
+   https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros
+
+ - Since rc.exe is a legacy compiler, it truncates long symbol (> 30 chars)
+   and reports warning "RC4011: identifier truncated".
+
+ - To eliminate the warning, we surround long preprocessor symbol with
+   "#if !defined(RC_INVOKED) ... #endif" block that means
+   "skip this block when rc.exe is trying to read it".
+</p></pre><BR>
+
 <pre><b>void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
 </b><p>  Use this to prepare an LZ4_stream_t for a new chain of dependent blocks
   (e.g., LZ4_compress_fast_continue()).
@@ -252,10 +273,55 @@
   LZ4_loadDict() triggers a reset, so any previous data will be forgotten.
   The same dictionary will have to be loaded on decompression side for successful decoding.
   Dictionary are useful for better compression of small data (KB range).
-  While LZ4 accept any input as dictionary,
-  results are generally better when using Zstandard's Dictionary Builder.
+  While LZ4 itself accepts any input as dictionary, dictionary efficiency is also a topic.
+  When in doubt, employ the Zstandard's Dictionary Builder.
   Loading a size of 0 is allowed, and is the same as reset.
- @return : loaded dictionary size, in bytes (necessarily <= 64 KB)
+ @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
+ 
+</p></pre><BR>
+
+<pre><b>int LZ4_loadDictSlow(LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
+</b><p>  Same as LZ4_loadDict(),
+  but uses a bit more cpu to reference the dictionary content more thoroughly.
+  This is expected to slightly improve compression ratio.
+  The extra-cpu cost is likely worth it if the dictionary is re-used across multiple sessions.
+ @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
+ 
+</p></pre><BR>
+
+<pre><b>void
+LZ4_attach_dictionary(LZ4_stream_t* workingStream,
+                const LZ4_stream_t* dictionaryStream);
+</b><p>
+  This allows efficient re-use of a static dictionary multiple times.
+
+  Rather than re-loading the dictionary buffer into a working context before
+  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
+  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
+  in which the working stream references @dictionaryStream in-place.
+
+  Several assumptions are made about the state of @dictionaryStream.
+  Currently, only states which have been prepared by LZ4_loadDict() or
+  LZ4_loadDictSlow() should be expected to work.
+
+  Alternatively, the provided @dictionaryStream may be NULL,
+  in which case any existing dictionary stream is unset.
+
+  If a dictionary is provided, it replaces any pre-existing stream history.
+  The dictionary contents are the only history that can be referenced and
+  logically immediately precede the data compressed in the first subsequent
+  compression call.
+
+  The dictionary will only remain attached to the working stream through the
+  first compression call, at the end of which it is cleared.
+ @dictionaryStream stream (and source buffer) must remain in-place / accessible / unchanged
+  through the completion of the compression session.
+
+  Note: there is no equivalent LZ4_attach_*() method on the decompression side
+  because there is no initialization cost, hence no need to share the cost across multiple sessions.
+  To decompress LZ4 blocks using dictionary, attached or not,
+  just employ the regular LZ4_setStreamDecode() for streaming,
+  or the stateless LZ4_decompress_safe_usingDict() for one-shot decompression.
  
 </p></pre><BR>
 
@@ -296,10 +362,12 @@
 <a name="Chapter7"></a><h2>Streaming Decompression Functions</h2><pre>  Bufferless synchronous API
 <BR></pre>
 
-<pre><b>#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
+<pre><b>#if !defined(RC_INVOKED) </b>/* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */<b>
+#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
 LZ4_streamDecode_t* LZ4_createStreamDecode(void);
 int                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
 #endif </b>/* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */<b>
+#endif
 </b><p>  creation / destruction of streaming decompression tracking context.
   A tracking context can be re-used multiple times.
  
@@ -332,10 +400,23 @@
 LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode,
                         const char* src, char* dst,
                         int srcSize, int dstCapacity);
-</b><p>  These decoding functions allow decompression of consecutive blocks in "streaming" mode.
-  A block is an unsplittable entity, it must be presented entirely to a decompression function.
-  Decompression functions only accepts one block at a time.
-  The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
+</b><p>  This decoding function allows decompression of consecutive blocks in "streaming" mode.
+  The difference with the usual independent blocks is that
+  new blocks are allowed to find references into former blocks.
+  A block is an unsplittable entity, and must be presented entirely to the decompression function.
+  LZ4_decompress_safe_continue() only accepts one block at a time.
+  It's modeled after `LZ4_decompress_safe()` and behaves similarly.
+
+ @LZ4_streamDecode : decompression state, tracking the position in memory of past data
+ @compressedSize : exact complete size of one compressed block.
+ @dstCapacity : size of destination buffer (which must be already allocated),
+                must be an upper bound of decompressed size.
+ @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
+           If destination buffer is not large enough, decoding will stop and output an error code (negative value).
+           If the source stream is detected malformed, the function will stop decoding and return a negative result.
+
+  The last 64KB of previously decoded data *must* remain available and unmodified
+  at the memory position where they were previously decoded.
   If less than 64KB of data has been decoded, all the data must be present.
 
   Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
@@ -361,15 +442,27 @@
 LZ4_decompress_safe_usingDict(const char* src, char* dst,
                               int srcSize, int dstCapacity,
                               const char* dictStart, int dictSize);
-</b><p>  These decoding functions work the same as
-  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
-  They are stand-alone, and don't need an LZ4_streamDecode_t structure.
+</b><p>  Works the same as
+  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue()
+  However, it's stateless: it doesn't need any LZ4_streamDecode_t state.
   Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
   Performance tip : Decompression speed can be substantially increased
                     when dst == dictStart + dictSize.
  
 </p></pre><BR>
 
+<pre><b>int
+LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
+                                      int compressedSize,
+                                      int targetOutputSize, int maxOutputSize,
+                                      const char* dictStart, int dictSize);
+</b><p>  Behaves the same as LZ4_decompress_safe_partial()
+  with the added ability to specify a memory segment for past data.
+  Performance tip : Decompression speed can be substantially increased
+                    when dst == dictStart + dictSize.
+ 
+</p></pre><BR>
+
 <a name="Chapter8"></a><h2>Experimental section</h2><pre>
  Symbols declared in this section must be considered unstable. Their
  signatures or semantics may change, or they may be removed altogether in the
@@ -400,33 +493,9 @@
  
 </p></pre><BR>
 
-<pre><b>LZ4LIB_STATIC_API void
-LZ4_attach_dictionary(LZ4_stream_t* workingStream,
-                const LZ4_stream_t* dictionaryStream);
-</b><p>  This is an experimental API that allows
-  efficient use of a static dictionary many times.
-
-  Rather than re-loading the dictionary buffer into a working context before
-  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
-  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
-  in which the working stream references the dictionary stream in-place.
-
-  Several assumptions are made about the state of the dictionary stream.
-  Currently, only streams which have been prepared by LZ4_loadDict() should
-  be expected to work.
-
-  Alternatively, the provided dictionaryStream may be NULL,
-  in which case any existing dictionary stream is unset.
-
-  If a dictionary is provided, it replaces any pre-existing stream history.
-  The dictionary contents are the only history that can be referenced and
-  logically immediately precede the data compressed in the first subsequent
-  compression call.
-
-  The dictionary will only remain attached to the working stream through the
-  first compression call, at the end of which it is cleared. The dictionary
-  stream (and source buffer) must remain in-place / accessible / unchanged
-  through the completion of the first compression call on the stream.
+<pre><b>int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration);
+</b><p>  Same as LZ4_compress_destSize(), but using an externally allocated state.
+  Also: exposes @acceleration
  
 </p></pre><BR>
 
@@ -496,7 +565,7 @@
   If you need static allocation, declare or allocate an LZ4_stream_t object.
 </p></pre><BR>
 
-<pre><b>LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);
+<pre><b>LZ4_stream_t* LZ4_initStream (void* stateBuffer, size_t size);
 </b><p>  An LZ4_stream_t structure must be initialized at least once.
   This is automatically done when invoking LZ4_createStream(),
   but it's not when the structure is simply declared on stack (for example).
@@ -568,11 +637,12 @@
 LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);
 </b><p></p></pre><BR>
 
-<pre><b>LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
+<pre><b>LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial() instead")
 int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
-LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
+LZ4_DEPRECATED("This function is deprecated and unsafe. Consider migrating towards LZ4_decompress_safe_continue() instead. "
+               "Note that the contract will change (requires block's compressed size, instead of decompressed size)")
 int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
-LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
+LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial_usingDict() instead")
 int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
 </b><p>  These functions used to be faster than LZ4_decompress_safe(),
   but this is no longer the case. They are now slower.
diff --git a/doc/lz4frame_manual.html b/doc/lz4frame_manual.html
index cfb437e..b3a021c 100644
--- a/doc/lz4frame_manual.html
+++ b/doc/lz4frame_manual.html
@@ -1,10 +1,10 @@
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
-<title>1.9.4 Manual</title>
+<title>1.10.0 Manual</title>
 </head>
 <body>
-<h1>1.9.4 Manual</h1>
+<h1>1.10.0 Manual</h1>
 <hr>
 <a name="Contents"></a><h2>Contents</h2>
 <ol>
@@ -18,7 +18,10 @@
 <li><a href="#Chapter8">Compression</a></li>
 <li><a href="#Chapter9">Decompression functions</a></li>
 <li><a href="#Chapter10">Streaming decompression functions</a></li>
-<li><a href="#Chapter11">Bulk processing dictionary API</a></li>
+<li><a href="#Chapter11">Dictionary compression API</a></li>
+<li><a href="#Chapter12">Bulk processing dictionary compression</a></li>
+<li><a href="#Chapter13">Advanced compression operations</a></li>
+<li><a href="#Chapter14">Custom memory allocation</a></li>
 </ol>
 <hr>
 <a name="Chapter1"></a><h2>Introduction</h2><pre>
@@ -76,13 +79,13 @@
 } LZ4F_frameType_t;
 </b></pre><BR>
 <pre><b>typedef struct {
-  LZ4F_blockSizeID_t     blockSizeID;         </b>/* max64KB, max256KB, max1MB, max4MB; 0 == default */<b>
-  LZ4F_blockMode_t       blockMode;           </b>/* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */<b>
-  LZ4F_contentChecksum_t contentChecksumFlag; </b>/* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */<b>
+  LZ4F_blockSizeID_t     blockSizeID;         </b>/* max64KB, max256KB, max1MB, max4MB; 0 == default (LZ4F_max64KB) */<b>
+  LZ4F_blockMode_t       blockMode;           </b>/* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default (LZ4F_blockLinked) */<b>
+  LZ4F_contentChecksum_t contentChecksumFlag; </b>/* 1: add a 32-bit checksum of frame's decompressed data; 0 == default (disabled) */<b>
   LZ4F_frameType_t       frameType;           </b>/* read-only field : LZ4F_frame or LZ4F_skippableFrame */<b>
   unsigned long long     contentSize;         </b>/* Size of uncompressed content ; 0 == unknown */<b>
   unsigned               dictID;              </b>/* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */<b>
-  LZ4F_blockChecksum_t   blockChecksumFlag;   </b>/* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */<b>
+  LZ4F_blockChecksum_t   blockChecksumFlag;   </b>/* 1: each block followed by a checksum of block's compressed data; 0 == default (disabled) */<b>
 } LZ4F_frameInfo_t;
 </b><p>  makes it possible to set or read frame parameters.
   Structure must be first init to 0, using memset() or LZ4F_INIT_FRAMEINFO,
@@ -105,6 +108,27 @@
 
 <a name="Chapter5"></a><h2>Simple compression function</h2><pre></pre>
 
+<pre><b>size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
+                                const void* srcBuffer, size_t srcSize,
+                                const LZ4F_preferences_t* preferencesPtr);
+</b><p>  Compress srcBuffer content into an LZ4-compressed frame.
+  It's a one shot operation, all input content is consumed, and all output is generated.
+
+  Note : it's a stateless operation (no LZ4F_cctx state needed).
+  In order to reduce load on the allocator, LZ4F_compressFrame(), by default,
+  uses the stack to allocate space for the compression state and some table.
+  If this usage of the stack is too much for your application,
+  consider compiling `lz4frame.c` with compile-time macro LZ4F_HEAPMODE set to 1 instead.
+  All state allocations will use the Heap.
+  It also means each invocation of LZ4F_compressFrame() will trigger several internal alloc/free invocations.
+
+ @dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
+ @preferencesPtr is optional : one can provide NULL, in which case all preferences are set to default.
+ @return : number of bytes written into dstBuffer.
+           or an error code if it fails (can be tested using LZ4F_isError())
+ 
+</p></pre><BR>
+
 <pre><b>size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
 </b><p>  Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences.
  `preferencesPtr` is optional. It can be replaced by NULL, in which case, the function will assume default preferences.
@@ -113,14 +137,8 @@
  
 </p></pre><BR>
 
-<pre><b>size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
-                                const void* srcBuffer, size_t srcSize,
-                                const LZ4F_preferences_t* preferencesPtr);
-</b><p>  Compress an entire srcBuffer into a valid LZ4 frame.
-  dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
-  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
- @return : number of bytes written into dstBuffer.
-           or an error code if it fails (can be tested using LZ4F_isError())
+<pre><b>int LZ4F_compressionLevel_max(void);   </b>/* v1.8.0+ */<b>
+</b><p> @return maximum allowed compression level (currently: 12)
  
 </p></pre><BR>
 
@@ -157,7 +175,7 @@
                                       const LZ4F_preferences_t* prefsPtr);
 </b><p>  will write the frame header into dstBuffer.
   dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default.
+ `prefsPtr` is optional : NULL can be provided to set all preferences to default.
  @return : number of bytes written into dstBuffer for the header
            or an error code (which can be tested using LZ4F_isError())
  
@@ -227,8 +245,9 @@
 <a name="Chapter9"></a><h2>Decompression functions</h2><pre></pre>
 
 <pre><b>typedef struct {
-  unsigned stableDst;     /* pledges that last 64KB decompressed data will remain available unmodified between invocations.
-                           * This optimization skips storage operations in tmp buffers. */
+  unsigned stableDst;     /* pledges that last 64KB decompressed data is present right before @dstBuffer pointer.
+                           * This optimization skips internal storage operations.
+                           * Once set, this pledge must remain valid up to the end of current frame. */
   unsigned skipChecksums; /* disable checksum calculation and verification, even when one is present in frame, to save CPU time.
                            * Setting this option to 1 once disables all checksums for the rest of the frame. */
   unsigned reserved1;     </b>/* must be set to zero for forward compatibility */<b>
@@ -329,6 +348,11 @@
  `dstBuffer` can freely change between each consecutive function invocation.
  `dstBuffer` content will be overwritten.
 
+  Note: if `LZ4F_getFrameInfo()` is called before `LZ4F_decompress()`, srcBuffer must be updated to reflect
+  the number of bytes consumed after reading the frame header. Failure to update srcBuffer before calling
+  `LZ4F_decompress()` will cause decompression failure or, even worse, successful but incorrect decompression.
+  See the `LZ4F_getFrameInfo()` docs for details.
+
  @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.
   Schematically, it's the size of the current (or remaining) compressed block + header of next block.
   Respecting the hint provides some small speed benefit, because it skips intermediate buffers.
@@ -353,74 +377,28 @@
   and start a new one using same context resources. 
 </p></pre><BR>
 
-<pre><b>typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
-              _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;
-</b></pre><BR>
-<pre><b>LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
-</b><p>  Return, in scalar format (size_t),
-  the maximum block size associated with blockSizeID.
-</p></pre><BR>
+<a name="Chapter11"></a><h2>Dictionary compression API</h2><pre></pre>
 
-<pre><b>LZ4FLIB_STATIC_API size_t
-LZ4F_uncompressedUpdate(LZ4F_cctx* cctx,
-                        void* dstBuffer, size_t dstCapacity,
-                  const void* srcBuffer, size_t srcSize,
-                  const LZ4F_compressOptions_t* cOptPtr);
-</b><p>  LZ4F_uncompressedUpdate() can be called repetitively to add as much data uncompressed data as necessary.
-  Important rule: dstCapacity MUST be large enough to store the entire source buffer as
-  no compression is done for this operation
-  If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode).
-  After an error, the state is left in a UB state, and must be re-initialized or freed.
-  If previously a compressed block was written, buffered data is flushed
-  before appending uncompressed data is continued.
-  This is only supported when LZ4F_blockIndependent is used
- `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
- @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
-           or an error code if it fails (which can be tested using LZ4F_isError())
+<pre><b>size_t
+LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
+                            void* dstBuffer, size_t dstCapacity,
+                      const void* dictBuffer, size_t dictSize,
+                      const LZ4F_preferences_t* prefsPtr);
+</b><p>  Inits dictionary compression streaming, and writes the frame header into dstBuffer.
+ @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
+ @prefsPtr is optional : one may provide NULL as argument,
+  however, it's the only way to provide dictID in the frame header.
+ @dictBuffer must outlive the compression session.
+ @return : number of bytes written into dstBuffer for the header,
+           or an error code (which can be tested using LZ4F_isError())
+  NOTE: The LZ4Frame spec allows each independent block to be compressed with the dictionary,
+        but this entry supports a more limited scenario, where only the first block uses the dictionary.
+        This is still useful for small data, which only need one block anyway.
+        For larger inputs, one may be more interested in LZ4F_compressFrame_usingCDict() below.
  
 </p></pre><BR>
 
-<a name="Chapter11"></a><h2>Bulk processing dictionary API</h2><pre></pre>
-
-<pre><b>LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
-LZ4FLIB_STATIC_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
-</b><p>  When compressing multiple messages / blocks using the same dictionary, it's recommended to load it just once.
-  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
-  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
- `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict 
-</p></pre><BR>
-
-<pre><b>LZ4FLIB_STATIC_API size_t
-LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
-                              void* dst, size_t dstCapacity,
-                        const void* src, size_t srcSize,
-                        const LZ4F_CDict* cdict,
-                        const LZ4F_preferences_t* preferencesPtr);
-</b><p>  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
-  cctx must point to a context created by LZ4F_createCompressionContext().
-  If cdict==NULL, compress without a dictionary.
-  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
-  If this condition is not respected, function will fail (@return an errorCode).
-  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,
-  but it's not recommended, as it's the only way to provide dictID in the frame header.
- @return : number of bytes written into dstBuffer.
-           or an error code if it fails (can be tested using LZ4F_isError()) 
-</p></pre><BR>
-
-<pre><b>LZ4FLIB_STATIC_API size_t
-LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
-                              void* dstBuffer, size_t dstCapacity,
-                        const LZ4F_CDict* cdict,
-                        const LZ4F_preferences_t* prefsPtr);
-</b><p>  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
-  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- `prefsPtr` is optional : you may provide NULL as argument,
-  however, it's the only way to provide dictID in the frame header.
- @return : number of bytes written into dstBuffer for the header,
-           or an error code (which can be tested using LZ4F_isError()) 
-</p></pre><BR>
-
-<pre><b>LZ4FLIB_STATIC_API size_t
+<pre><b>size_t
 LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
                           void* dstBuffer, size_t* dstSizePtr,
                     const void* srcBuffer, size_t* srcSizePtr,
@@ -431,6 +409,81 @@
   It must remain accessible throughout the entire frame decoding. 
 </p></pre><BR>
 
+<a name="Chapter12"></a><h2>Bulk processing dictionary compression</h2><pre></pre>
+
+<pre><b>LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
+void        LZ4F_freeCDict(LZ4F_CDict* CDict);
+</b><p>  When compressing multiple messages / blocks using the same dictionary, it's recommended to initialize it just once.
+  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
+  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
+ @dictBuffer can be released after LZ4_CDict creation, since its content is copied within CDict. 
+</p></pre><BR>
+
+<pre><b>size_t
+LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
+                              void* dst, size_t dstCapacity,
+                        const void* src, size_t srcSize,
+                        const LZ4F_CDict* cdict,
+                        const LZ4F_preferences_t* preferencesPtr);
+</b><p>  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
+ @cctx must point to a context created by LZ4F_createCompressionContext().
+  If @cdict==NULL, compress without a dictionary.
+ @dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
+  If this condition is not respected, function will fail (@return an errorCode).
+  The LZ4F_preferences_t structure is optional : one may provide NULL as argument,
+  but it's not recommended, as it's the only way to provide @dictID in the frame header.
+ @return : number of bytes written into dstBuffer.
+           or an error code if it fails (can be tested using LZ4F_isError())
+  Note: for larger inputs generating multiple independent blocks,
+        this entry point uses the dictionary for each block. 
+</p></pre><BR>
+
+<pre><b>size_t
+LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
+                              void* dstBuffer, size_t dstCapacity,
+                        const LZ4F_CDict* cdict,
+                        const LZ4F_preferences_t* prefsPtr);
+</b><p>  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
+ @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
+ @prefsPtr is optional : one may provide NULL as argument,
+  note however that it's the only way to insert a @dictID in the frame header.
+ @cdict must outlive the compression session.
+ @return : number of bytes written into dstBuffer for the header,
+           or an error code, which can be tested using LZ4F_isError(). 
+</p></pre><BR>
+
+<pre><b>typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
+              _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;
+</b></pre><BR>
+<a name="Chapter13"></a><h2>Advanced compression operations</h2><pre></pre>
+
+<pre><b>LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
+</b><p> @return, in scalar format (size_t),
+          the maximum block size associated with @blockSizeID,
+          or an error code (can be tested using LZ4F_isError()) if @blockSizeID is invalid.
+</p></pre><BR>
+
+<pre><b>LZ4FLIB_STATIC_API size_t
+LZ4F_uncompressedUpdate(LZ4F_cctx* cctx,
+                        void* dstBuffer, size_t dstCapacity,
+                  const void* srcBuffer, size_t srcSize,
+                  const LZ4F_compressOptions_t* cOptPtr);
+</b><p>  LZ4F_uncompressedUpdate() can be called repetitively to add data stored as uncompressed blocks.
+  Important rule: dstCapacity MUST be large enough to store the entire source buffer as
+  no compression is done for this operation
+  If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode).
+  After an error, the state is left in a UB state, and must be re-initialized or freed.
+  If previously a compressed block was written, buffered data is flushed first,
+  before appending uncompressed data is continued.
+  This operation is only supported when LZ4F_blockIndependent is used.
+ `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
+ @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
+           or an error code if it fails (which can be tested using LZ4F_isError())
+ 
+</p></pre><BR>
+
+<a name="Chapter14"></a><h2>Custom memory allocation</h2><pre></pre>
+
 <pre><b>typedef void* (*LZ4F_AllocFunction) (void* opaqueState, size_t size);
 typedef void* (*LZ4F_CallocFunction) (void* opaqueState, size_t size);
 typedef void  (*LZ4F_FreeFunction) (void* opaqueState, void* address);
diff --git a/examples/.gitignore b/examples/.gitignore
index ddc8e21..521d144 100644
--- a/examples/.gitignore
+++ b/examples/.gitignore
@@ -1,11 +1,12 @@
 /Makefile.lz4*
-/printVersion
-/doubleBuffer
-/dictionaryRandomAccess
-/ringBuffer
-/ringBufferHC
-/lineCompress
+/print_version
+/simple_buffer
 /frameCompress
 /fileCompress
-/simpleBuffer
+/blockStreaming_doubleBuffer
+/blockStreaming_ringBuffer
+/streamingHC_ringBuffer
+/blockStreaming_lineByLine
+/dictionaryRandomAccess
+/bench_functions
 /*.exe
diff --git a/examples/COPYING b/examples/COPYING
index d159169..c728282 100644
--- a/examples/COPYING
+++ b/examples/COPYING
@@ -1,339 +1,83 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
+Full name:
+GNU General Public License v2.0 or later
 
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+Short identifier:
+GPL-2.0-or-later
 
-                            Preamble
+Text:
+GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991
 
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
 
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
+Preamble
 
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
 
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
 
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
+To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
 
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
 
-  The precise terms and conditions for copying, distribution and
-modification follow.
+We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
 
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
 
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
+Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
 
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
+The precise terms and conditions for copying, distribution and modification follow.
 
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
+0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
 
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
+1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
 
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
+2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
+b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
+c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
 
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
 
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
+In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
 
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
+3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
+a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
 
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
+If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
 
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
+4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
 
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
+5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
 
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
+6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
 
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
+7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
 
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
 
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
 
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
+8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
 
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
+9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
 
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
+10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+NO WARRANTY
 
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
diff --git a/examples/Makefile b/examples/Makefile
index 8be5c81..91a4f48 100644
--- a/examples/Makefile
+++ b/examples/Makefile
@@ -27,71 +27,57 @@
 # kindly provided by Takayuki Matsuoka
 # ##########################################################################
 
-CPPFLAGS += -I../lib
-CFLAGS   ?= -O3
-CFLAGS   += -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wstrict-prototypes
-FLAGS    := $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(MOREFLAGS)
+LIBDIR    := ../lib
 
-TESTFILE  = Makefile
-LZ4DIR   := ../lib
-LZ4       = ../programs/lz4
+CPPFLAGS  += -I$(LIBDIR)
+USERCFLAGS:= $(CFLAGS)
+WFLAGS     = -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wc++-compat
+CFLAGS     = $(WFLAGS) -O2 $(USERCFLAGS)
 
-include ../Makefile.inc
+TESTFILE   = Makefile
+SLIBLZ4   := $(LIBDIR)/liblz4.a
+LZ4DIR     = ../programs
+LZ4        = $(LZ4DIR)/lz4
 
 default: all
 
-all: printVersion doubleBuffer dictionaryRandomAccess ringBuffer ringBufferHC \
-     lineCompress frameCompress fileCompress simpleBuffer
+$(SLIBLZ4): $(LIBDIR)/lz4.c $(LIBDIR)/lz4hc.c $(LIBDIR)/lz4frame.c $(LIBDIR)/lz4.h $(LIBDIR)/lz4hc.h $(LIBDIR)/lz4frame.h $(LIBDIR)/lz4frame_static.h
+	$(MAKE) -j -C $(LIBDIR) liblz4.a
 
-$(LZ4DIR)/liblz4.a: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c $(LZ4DIR)/lz4.h $(LZ4DIR)/lz4hc.h $(LZ4DIR)/lz4frame.h $(LZ4DIR)/lz4frame_static.h
-	$(MAKE) -C $(LZ4DIR) liblz4.a
+ALL = print_version \
+	  simple_buffer \
+	  frameCompress \
+	  fileCompress \
+      blockStreaming_doubleBuffer \
+	  blockStreaming_ringBuffer \
+	  streamingHC_ringBuffer \
+      blockStreaming_lineByLine \
+	  dictionaryRandomAccess \
+	  bench_functions
 
-printVersion: printVersion.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+.PHONY: all
+all: $(ALL)
 
-doubleBuffer: blockStreaming_doubleBuffer.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+$(ALL): $(SLIBLZ4)
 
-dictionaryRandomAccess: dictionaryRandomAccess.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-ringBuffer  : blockStreaming_ringBuffer.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-ringBufferHC: HCStreaming_ringBuffer.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-lineCompress: blockStreaming_lineByLine.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-frameCompress: frameCompress.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-fileCompress: fileCompress.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-compressFunctions: compress_functions.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT) -lrt
-
-simpleBuffer: simple_buffer.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
+.PHONY:$(LZ4)
 $(LZ4) :
-	$(MAKE) -C ../programs lz4
+	$(MAKE) -j -C $(LZ4DIR) lz4
 
+.PHONY: test
 test : all $(LZ4)
 	@echo "\n=== Print Version ==="
-	./printVersion$(EXT)
+	./print_version$(EXT)
 	@echo "\n=== Simple compression example ==="
-	./simpleBuffer$(EXT)
+	./simple_buffer$(EXT)
 	@echo "\n=== Double-buffer ==="
-	./doubleBuffer$(EXT) $(TESTFILE)
+	./blockStreaming_doubleBuffer$(EXT) $(TESTFILE)
 	@echo "\n=== Ring Buffer ==="
-	./ringBuffer$(EXT)   $(TESTFILE)
+	./blockStreaming_ringBuffer$(EXT)   $(TESTFILE)
 	@echo "\n=== Ring Buffer + LZ4 HC ==="
-	./ringBufferHC$(EXT) $(TESTFILE)
+	./streamingHC_ringBuffer$(EXT) $(TESTFILE)
 	@echo "\n=== Compress line by line ==="
-	./lineCompress$(EXT) $(TESTFILE)
+	./blockStreaming_lineByLine$(EXT) $(TESTFILE)
 	@echo "\n=== Dictionary Random Access ==="
 	./dictionaryRandomAccess$(EXT) $(TESTFILE) $(TESTFILE) 1100 1400
 	@echo "\n=== Frame compression ==="
@@ -100,15 +86,10 @@
 	@echo "\n=== file compression ==="
 	./fileCompress$(EXT) $(TESTFILE)
 	$(LZ4) -vt $(TESTFILE).lz4
+	@echo "\n=== Q&D benchmark ==="
+	./bench_functions$(EXT) 10000
 
-.PHONY: cxxtest
-cxxtest: CFLAGS := -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror
-cxxtest: clean
-	CC=$(CXX) $(MAKE) -C . all CFLAGS="$(CFLAGS)"
-
+.PHONY: clean
 clean:
-	@rm -f core *.o *.dec *-0 *-9 *-8192 *.lz4s *.lz4 \
-	 printVersion$(EXT) doubleBuffer$(EXT) dictionaryRandomAccess$(EXT) \
-	 ringBuffer$(EXT) ringBufferHC$(EXT) lineCompress$(EXT) frameCompress$(EXT) \
-	 fileCompress$(EXT) compressFunctions$(EXT) simpleBuffer$(EXT)
+	@$(RM) core *.o *.dec *-0 *-9 *-8192 *.lz4s *.lz4 $(ALL)
 	@echo Cleaning completed
diff --git a/examples/compress_functions.c b/examples/bench_functions.c
similarity index 77%
rename from examples/compress_functions.c
rename to examples/bench_functions.c
index 2a9d124..67b08ee 100644
--- a/examples/compress_functions.c
+++ b/examples/bench_functions.c
@@ -1,5 +1,5 @@
 /*
- * compress_functions.c
+ * bench_functions.c
  * Copyright  : Kyle Harper
  * License    : Follows same licensing as the lz4.c/lz4.h program at any given time.  Currently, BSD 2.
  * Description: A program to demonstrate the various compression functions involved in when using LZ4_compress_default().  The idea
@@ -67,8 +67,10 @@
 #include <string.h>   /* for atoi() memcmp() */
 #include <stdint.h>   /* for uint_types */
 #include <inttypes.h> /* for PRIu64 */
-#include <time.h>     /* for clock_gettime() */
+#include <time.h>     /* for clock() */
 #include <locale.h>   /* for setlocale() */
+#include <limits.h>   /* for INT_MAX */
+#include <assert.h>
 
 /* We need to know what one billion is for clock timing. */
 #define BILLION 1000000000L
@@ -82,46 +84,45 @@
 #define ID__LZ4_DECOMPRESS_FAST         6
 
 
-
 /*
  * Easy show-error-and-bail function.
  */
 void run_screaming(const char *message, const int code) {
-  printf("%s\n", message);
+  printf("%s \n", message);
   exit(code);
 }
 
-
 /*
  * Centralize the usage function to keep main cleaner.
  */
-void usage(const char *message) {
-  printf("Usage: ./argPerformanceTesting <iterations>\n");
+void usage(const char* exeName, const char* message) {
+  printf("Usage: %s <iterations> \n", exeName);
   run_screaming(message, 1);
   return;
 }
 
+#define CHECK(c) { if (!(c)) { run_screaming(#c, 1); } }
 
 
 /*
- * Runs the benchmark for LZ4_compress_* based on function_id.
+ * Runs the benchmark for LZ4_* function based on function_id.
+ * @return : benchmark duration, in ns
  */
 uint64_t bench(
     const char *known_good_dst,
     const int function_id,
-    const int iterations,
+    int iterations,
     const char *src,
     char *dst,
     const size_t src_size,
     const size_t max_dst_size,
     const size_t comp_size
   ) {
-  uint64_t time_taken = 0;
   int rv = 0;
   const int warm_up = 5000;
-  struct timespec start, end;
   const int acceleration = 1;
   LZ4_stream_t state;
+  clock_t start = clock();
 
   // Select the right function to perform the benchmark on.  We perform 5000 initial loops to warm the cache and ensure that dst
   // remains matching to known_good_dst between successive calls.
@@ -129,40 +130,40 @@
     case ID__LZ4_COMPRESS_DEFAULT:
       printf("Starting benchmark for function: LZ4_compress_default()\n");
       for(int junk=0; junk<warm_up; junk++)
-        rv = LZ4_compress_default(src, dst, src_size, max_dst_size);
+        rv = LZ4_compress_default(src, dst, (int)src_size, (int)max_dst_size);
       if (rv < 1)
         run_screaming("Couldn't run LZ4_compress_default()... error code received is in exit code.", rv);
       if (memcmp(known_good_dst, dst, max_dst_size) != 0)
         run_screaming("According to memcmp(), the compressed dst we got doesn't match the known_good_dst... ruh roh.", 1);
-      clock_gettime(CLOCK_MONOTONIC, &start);
+      start = clock();
       for (int i=1; i<=iterations; i++)
-        LZ4_compress_default(src, dst, src_size, max_dst_size);
+        LZ4_compress_default(src, dst, (int)src_size, (int)max_dst_size);
       break;
 
     case ID__LZ4_COMPRESS_FAST:
       printf("Starting benchmark for function: LZ4_compress_fast()\n");
       for(int junk=0; junk<warm_up; junk++)
-        rv = LZ4_compress_fast(src, dst, src_size, max_dst_size, acceleration);
+        rv = LZ4_compress_fast(src, dst, (int)src_size, (int)max_dst_size, acceleration);
       if (rv < 1)
         run_screaming("Couldn't run LZ4_compress_fast()... error code received is in exit code.", rv);
       if (memcmp(known_good_dst, dst, max_dst_size) != 0)
         run_screaming("According to memcmp(), the compressed dst we got doesn't match the known_good_dst... ruh roh.", 1);
-      clock_gettime(CLOCK_MONOTONIC, &start);
+      start = clock();
       for (int i=1; i<=iterations; i++)
-        LZ4_compress_fast(src, dst, src_size, max_dst_size, acceleration);
+        LZ4_compress_fast(src, dst, (int)src_size, (int)max_dst_size, acceleration);
       break;
 
     case ID__LZ4_COMPRESS_FAST_EXTSTATE:
       printf("Starting benchmark for function: LZ4_compress_fast_extState()\n");
       for(int junk=0; junk<warm_up; junk++)
-        rv = LZ4_compress_fast_extState(&state, src, dst, src_size, max_dst_size, acceleration);
+        rv = LZ4_compress_fast_extState(&state, src, dst, (int)src_size, (int)max_dst_size, acceleration);
       if (rv < 1)
         run_screaming("Couldn't run LZ4_compress_fast_extState()... error code received is in exit code.", rv);
       if (memcmp(known_good_dst, dst, max_dst_size) != 0)
         run_screaming("According to memcmp(), the compressed dst we got doesn't match the known_good_dst... ruh roh.", 1);
-      clock_gettime(CLOCK_MONOTONIC, &start);
+      start = clock();
       for (int i=1; i<=iterations; i++)
-        LZ4_compress_fast_extState(&state, src, dst, src_size, max_dst_size, acceleration);
+        LZ4_compress_fast_extState(&state, src, dst, (int)src_size, (int)max_dst_size, acceleration);
       break;
 
 //    Disabled until LZ4_compress_generic() is exposed in the header.
@@ -188,27 +189,27 @@
     case ID__LZ4_DECOMPRESS_SAFE:
       printf("Starting benchmark for function: LZ4_decompress_safe()\n");
       for(int junk=0; junk<warm_up; junk++)
-        rv = LZ4_decompress_safe(src, dst, comp_size, src_size);
+        rv = LZ4_decompress_safe(src, dst, (int)comp_size, (int)src_size);
       if (rv < 1)
         run_screaming("Couldn't run LZ4_decompress_safe()... error code received is in exit code.", rv);
       if (memcmp(known_good_dst, dst, src_size) != 0)
         run_screaming("According to memcmp(), the compressed dst we got doesn't match the known_good_dst... ruh roh.", 1);
-      clock_gettime(CLOCK_MONOTONIC, &start);
+      start = clock();
       for (int i=1; i<=iterations; i++)
-        LZ4_decompress_safe(src, dst, comp_size, src_size);
+        LZ4_decompress_safe(src, dst, (int)comp_size, (int)src_size);
       break;
 
     case ID__LZ4_DECOMPRESS_FAST:
       printf("Starting benchmark for function: LZ4_decompress_fast()\n");
       for(int junk=0; junk<warm_up; junk++)
-        rv = LZ4_decompress_fast(src, dst, src_size);
+        rv = LZ4_decompress_fast(src, dst, (int)src_size);
       if (rv < 1)
         run_screaming("Couldn't run LZ4_decompress_fast()... error code received is in exit code.", rv);
       if (memcmp(known_good_dst, dst, src_size) != 0)
         run_screaming("According to memcmp(), the compressed dst we got doesn't match the known_good_dst... ruh roh.", 1);
-      clock_gettime(CLOCK_MONOTONIC, &start);
+      start = clock();
       for (int i=1; i<=iterations; i++)
-        LZ4_decompress_fast(src, dst, src_size);
+        LZ4_decompress_fast(src, dst, (int)src_size);
       break;
 
     default:
@@ -216,15 +217,21 @@
       break;
   }
 
-  // Stop timer and return time taken.
-  clock_gettime(CLOCK_MONOTONIC, &end);
-  time_taken = BILLION *(end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
+  { clock_t end = clock();
 
-  return time_taken;
+    // Low resolution timer => requires more iterations to measure something
+    if (end == start) {
+      assert(iterations < (INT_MAX / 10));
+      iterations *= 10;
+      printf("not enough iterations => increase nb of iterations to %i \n", iterations);
+      return bench(known_good_dst, function_id, iterations, src, dst, src_size, max_dst_size, comp_size);
+    }
+
+    return (uint64_t)((double)(end - start) / CLOCKS_PER_SEC * BILLION);
+  }
 }
 
 
-
 /*
  * main()
  * We will demonstrate the use of each function for simplicity sake.  Then we will run 2 suites of benchmarking:
@@ -235,32 +242,33 @@
  */
 int main(int argc, char **argv) {
   // Get and verify options.  There's really only 1:  How many iterations to run.
+  const char* exeName = argv[0];
   int iterations = 1000000;
   if (argc > 1)
     iterations = atoi(argv[1]);
   if (iterations < 1)
-    usage("Argument 1 (iterations) must be > 0.");
+    usage(exeName, "Argument 1 (iterations) must be > 0.");
 
   // First we will create 2 sources (char *) of 2000 bytes each.  One normal text, the other highly-compressible text.
-  const char *src    = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus purus et risus vulputate, et mollis orci ullamcorper. Nulla facilisi. Fusce in ligula sed purus varius aliquet interdum vitae justo. Proin quis diam velit. Nulla varius iaculis auctor. Cras volutpat, justo eu dictum pulvinar, elit sem porttitor metus, et imperdiet metus sapien et ante. Nullam nisi nulla, ornare eu tristique eu, dignissim vitae diam. Nulla sagittis porta libero, a accumsan felis sagittis scelerisque.  Integer laoreet eleifend congue. Etiam rhoncus leo vel dolor fermentum, quis luctus nisl iaculis. Praesent a erat sapien. Aliquam semper mi in lorem ultrices ultricies. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat risus sed enim ultrices, at sodales nulla tristique. Maecenas eget pellentesque justo, sed pellentesque lectus. Fusce sagittis sit amet elit vel varius. Donec sed ligula nec ligula vulputate rutrum sed ut lectus. Etiam congue pharetra leo vitae cursus. Morbi enim ante, porttitor ut varius vel, tincidunt quis justo. Nunc iaculis, risus id ultrices semper, metus est efficitur ligula, vel posuere risus nunc eget purus. Ut lorem turpis, condimentum at sem sed, porta aliquam turpis. In ut sapien a nulla dictum tincidunt quis sit amet lorem. Fusce at est egestas, luctus neque eu, consectetur tortor. Phasellus eleifend ultricies nulla ac lobortis.  Morbi maximus quam cursus vehicula iaculis. Maecenas cursus vel justo ut rutrum. Curabitur magna orci, dignissim eget dapibus vitae, finibus id lacus. Praesent rhoncus mattis augue vitae bibendum. Praesent porta mauris non ultrices fermentum. Quisque vulputate ipsum in sodales pulvinar. Aliquam nec mollis felis. Donec vitae augue pulvinar, congue nisl sed, pretium purus. Fusce lobortis mi ac neque scelerisque semper. Pellentesque vel est vitae magna aliquet aliquet. Nam non dolor. Nulla facilisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi ac lacinia felis metus.";
-  const char *hc_src = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+  const char src[]    = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus purus et risus vulputate, et mollis orci ullamcorper. Nulla facilisi. Fusce in ligula sed purus varius aliquet interdum vitae justo. Proin quis diam velit. Nulla varius iaculis auctor. Cras volutpat, justo eu dictum pulvinar, elit sem porttitor metus, et imperdiet metus sapien et ante. Nullam nisi nulla, ornare eu tristique eu, dignissim vitae diam. Nulla sagittis porta libero, a accumsan felis sagittis scelerisque.  Integer laoreet eleifend congue. Etiam rhoncus leo vel dolor fermentum, quis luctus nisl iaculis. Praesent a erat sapien. Aliquam semper mi in lorem ultrices ultricies. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat risus sed enim ultrices, at sodales nulla tristique. Maecenas eget pellentesque justo, sed pellentesque lectus. Fusce sagittis sit amet elit vel varius. Donec sed ligula nec ligula vulputate rutrum sed ut lectus. Etiam congue pharetra leo vitae cursus. Morbi enim ante, porttitor ut varius vel, tincidunt quis justo. Nunc iaculis, risus id ultrices semper, metus est efficitur ligula, vel posuere risus nunc eget purus. Ut lorem turpis, condimentum at sem sed, porta aliquam turpis. In ut sapien a nulla dictum tincidunt quis sit amet lorem. Fusce at est egestas, luctus neque eu, consectetur tortor. Phasellus eleifend ultricies nulla ac lobortis.  Morbi maximus quam cursus vehicula iaculis. Maecenas cursus vel justo ut rutrum. Curabitur magna orci, dignissim eget dapibus vitae, finibus id lacus. Praesent rhoncus mattis augue vitae bibendum. Praesent porta mauris non ultrices fermentum. Quisque vulputate ipsum in sodales pulvinar. Aliquam nec mollis felis. Donec vitae augue pulvinar, congue nisl sed, pretium purus. Fusce lobortis mi ac neque scelerisque semper. Pellentesque vel est vitae magna aliquet aliquet. Nam non dolor. Nulla facilisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi ac lacinia felis metus.";
+  const char hc_src[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
   // Set and derive sizes.  Since we're using strings, use strlen() + 1 for \0.
   const size_t src_size = strlen(src) + 1;
-  const size_t max_dst_size = LZ4_compressBound(src_size);
+  const size_t max_dst_size = (size_t)LZ4_compressBound((int)src_size);
   int bytes_returned = 0;
   // Now build allocations for the data we'll be playing with.
-  char *dst               = calloc(1, max_dst_size);
-  char *known_good_dst    = calloc(1, max_dst_size);
-  char *known_good_hc_dst = calloc(1, max_dst_size);
+  char *dst               = (char*)calloc(1, max_dst_size);
+  char *known_good_dst    = (char*)calloc(1, max_dst_size);
+  char *known_good_hc_dst = (char*)calloc(1, max_dst_size);
   if (dst == NULL || known_good_dst == NULL || known_good_hc_dst == NULL)
     run_screaming("Couldn't allocate memory for the destination buffers.  Sad :(", 1);
 
   // Create known-good buffers to verify our tests with other functions will produce the same results.
-  bytes_returned = LZ4_compress_default(src, known_good_dst, src_size, max_dst_size);
+  bytes_returned = LZ4_compress_default(src, known_good_dst, (int)src_size, (int)max_dst_size);
   if (bytes_returned < 1)
     run_screaming("Couldn't create a known-good destination buffer for comparison... this is bad.", 1);
   const size_t src_comp_size = bytes_returned;
-  bytes_returned = LZ4_compress_default(hc_src, known_good_hc_dst, src_size, max_dst_size);
+  bytes_returned = LZ4_compress_default(hc_src, known_good_hc_dst, (int)src_size, (int)max_dst_size);
   if (bytes_returned < 1)
     run_screaming("Couldn't create a known-good (highly compressible) destination buffer for comparison... this is bad.", 1);
   const size_t hc_src_comp_size = bytes_returned;
@@ -272,7 +280,7 @@
   /* LZ4_compress_fast() */
   // Using this function is identical to LZ4_compress_default except we need to specify an "acceleration" value.  Defaults to 1.
   memset(dst, 0, max_dst_size);
-  bytes_returned = LZ4_compress_fast(src, dst, src_size, max_dst_size, 1);
+  bytes_returned = LZ4_compress_fast(src, dst, (int)src_size, (int)max_dst_size, 1);
   if (bytes_returned < 1)
     run_screaming("Failed to compress src using LZ4_compress_fast.  echo $? for return code.", bytes_returned);
   if (memcmp(dst, known_good_dst, bytes_returned) != 0)
@@ -282,7 +290,7 @@
   // Using this function directly requires that we build an LZ4_stream_t struct ourselves.  We do NOT have to reset it ourselves.
   memset(dst, 0, max_dst_size);
   LZ4_stream_t state;
-  bytes_returned = LZ4_compress_fast_extState(&state, src, dst, src_size, max_dst_size, 1);
+  bytes_returned = LZ4_compress_fast_extState(&state, src, dst, (int)src_size, (int)max_dst_size, 1);
   if (bytes_returned < 1)
     run_screaming("Failed to compress src using LZ4_compress_fast_extState.  echo $? for return code.", bytes_returned);
   if (memcmp(dst, known_good_dst, bytes_returned) != 0)
@@ -315,7 +323,8 @@
    * Remember, we cannot call LZ4_compress_generic() directly (yet) so it's disabled.
    */
   // Suite A - Normal Compressibility
-  char *dst_d = calloc(1, src_size);
+  char *dst_d = (char*)calloc(1, src_size);
+  CHECK(dst_d!=NULL);
   memset(dst, 0, max_dst_size);
   printf("\nStarting suite A:  Normal compressible text.\n");
   uint64_t time_taken__default       = bench(known_good_dst, ID__LZ4_COMPRESS_DEFAULT,       iterations, src,            dst,   src_size, max_dst_size, src_comp_size);
@@ -336,26 +345,27 @@
 
   // Report and leave.
   setlocale(LC_ALL, "");
-  const char *format        = "|%-14s|%-30s|%'14.9f|%'16d|%'14d|%'13.2f%%|\n";
+  const char *format        = "|%-14s|%-30s|%'14.9f|%'16d|%'14llu|%'13.2f%%|\n";
   const char *header_format = "|%-14s|%-30s|%14s|%16s|%14s|%14s|\n";
   const char *separator     = "+--------------+------------------------------+--------------+----------------+--------------+--------------+\n";
+  uint64_t iterllu = (uint64_t)iterations;
   printf("\n");
   printf("%s", separator);
   printf(header_format, "Source", "Function Benchmarked", "Total Seconds", "Iterations/sec", "ns/Iteration", "% of default");
   printf("%s", separator);
-  printf(format, "Normal Text", "LZ4_compress_default()",       (double)time_taken__default       / BILLION, (int)(iterations / ((double)time_taken__default       /BILLION)), (int)time_taken__default       / iterations, (double)time_taken__default       * 100 / time_taken__default);
-  printf(format, "Normal Text", "LZ4_compress_fast()",          (double)time_taken__fast          / BILLION, (int)(iterations / ((double)time_taken__fast          /BILLION)), (int)time_taken__fast          / iterations, (double)time_taken__fast          * 100 / time_taken__default);
-  printf(format, "Normal Text", "LZ4_compress_fast_extState()", (double)time_taken__fast_extstate / BILLION, (int)(iterations / ((double)time_taken__fast_extstate /BILLION)), (int)time_taken__fast_extstate / iterations, (double)time_taken__fast_extstate * 100 / time_taken__default);
+  printf(format, "Normal Text", "LZ4_compress_default()",       (double)time_taken__default       / BILLION, (int)(iterations / ((double)time_taken__default       /BILLION)), time_taken__default       / iterllu, (double)time_taken__default       * 100 / time_taken__default);
+  printf(format, "Normal Text", "LZ4_compress_fast()",          (double)time_taken__fast          / BILLION, (int)(iterations / ((double)time_taken__fast          /BILLION)), time_taken__fast          / iterllu, (double)time_taken__fast          * 100 / time_taken__default);
+  printf(format, "Normal Text", "LZ4_compress_fast_extState()", (double)time_taken__fast_extstate / BILLION, (int)(iterations / ((double)time_taken__fast_extstate /BILLION)), time_taken__fast_extstate / iterllu, (double)time_taken__fast_extstate * 100 / time_taken__default);
   //printf(format, "Normal Text", "LZ4_compress_generic()",       (double)time_taken__generic       / BILLION, (int)(iterations / ((double)time_taken__generic       /BILLION)), (int)time_taken__generic       / iterations, (double)time_taken__generic       * 100 / time_taken__default);
-  printf(format, "Normal Text", "LZ4_decompress_safe()",        (double)time_taken__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken__decomp_safe   /BILLION)), (int)time_taken__decomp_safe   / iterations, (double)time_taken__decomp_safe   * 100 / time_taken__default);
-  printf(format, "Normal Text", "LZ4_decompress_fast()",        (double)time_taken__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken__decomp_fast   /BILLION)), (int)time_taken__decomp_fast   / iterations, (double)time_taken__decomp_fast   * 100 / time_taken__default);
+  printf(format, "Normal Text", "LZ4_decompress_safe()",        (double)time_taken__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken__decomp_safe   /BILLION)), time_taken__decomp_safe   / iterllu, (double)time_taken__decomp_safe   * 100 / time_taken__default);
+  printf(format, "Normal Text", "LZ4_decompress_fast()",        (double)time_taken__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken__decomp_fast   /BILLION)), time_taken__decomp_fast   / iterllu, (double)time_taken__decomp_fast   * 100 / time_taken__default);
   printf(header_format, "", "", "", "", "", "");
-  printf(format, "Compressible", "LZ4_compress_default()",       (double)time_taken_hc__default       / BILLION, (int)(iterations / ((double)time_taken_hc__default       /BILLION)), (int)time_taken_hc__default       / iterations, (double)time_taken_hc__default       * 100 / time_taken_hc__default);
-  printf(format, "Compressible", "LZ4_compress_fast()",          (double)time_taken_hc__fast          / BILLION, (int)(iterations / ((double)time_taken_hc__fast          /BILLION)), (int)time_taken_hc__fast          / iterations, (double)time_taken_hc__fast          * 100 / time_taken_hc__default);
-  printf(format, "Compressible", "LZ4_compress_fast_extState()", (double)time_taken_hc__fast_extstate / BILLION, (int)(iterations / ((double)time_taken_hc__fast_extstate /BILLION)), (int)time_taken_hc__fast_extstate / iterations, (double)time_taken_hc__fast_extstate * 100 / time_taken_hc__default);
+  printf(format, "Compressible", "LZ4_compress_default()",       (double)time_taken_hc__default       / BILLION, (int)(iterations / ((double)time_taken_hc__default       /BILLION)), time_taken_hc__default       / iterllu, (double)time_taken_hc__default       * 100 / time_taken_hc__default);
+  printf(format, "Compressible", "LZ4_compress_fast()",          (double)time_taken_hc__fast          / BILLION, (int)(iterations / ((double)time_taken_hc__fast          /BILLION)), time_taken_hc__fast          / iterllu, (double)time_taken_hc__fast          * 100 / time_taken_hc__default);
+  printf(format, "Compressible", "LZ4_compress_fast_extState()", (double)time_taken_hc__fast_extstate / BILLION, (int)(iterations / ((double)time_taken_hc__fast_extstate /BILLION)), time_taken_hc__fast_extstate / iterllu, (double)time_taken_hc__fast_extstate * 100 / time_taken_hc__default);
   //printf(format, "Compressible", "LZ4_compress_generic()",       (double)time_taken_hc__generic       / BILLION, (int)(iterations / ((double)time_taken_hc__generic       /BILLION)), (int)time_taken_hc__generic       / iterations, (double)time_taken_hc__generic       * 100 / time_taken_hc__default);
-  printf(format, "Compressible", "LZ4_decompress_safe()",        (double)time_taken_hc__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_safe   /BILLION)), (int)time_taken_hc__decomp_safe   / iterations, (double)time_taken_hc__decomp_safe   * 100 / time_taken_hc__default);
-  printf(format, "Compressible", "LZ4_decompress_fast()",        (double)time_taken_hc__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_fast   /BILLION)), (int)time_taken_hc__decomp_fast   / iterations, (double)time_taken_hc__decomp_fast   * 100 / time_taken_hc__default);
+  printf(format, "Compressible", "LZ4_decompress_safe()",        (double)time_taken_hc__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_safe   /BILLION)), time_taken_hc__decomp_safe   / iterllu, (double)time_taken_hc__decomp_safe   * 100 / time_taken_hc__default);
+  printf(format, "Compressible", "LZ4_decompress_fast()",        (double)time_taken_hc__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_fast   /BILLION)), time_taken_hc__decomp_fast   / iterllu, (double)time_taken_hc__decomp_fast   * 100 / time_taken_hc__default);
   printf("%s", separator);
   printf("\n");
   printf("All done, ran %d iterations per test.\n", iterations);
diff --git a/examples/fileCompress.c b/examples/fileCompress.c
index 4486ea8..81f8067 100644
--- a/examples/fileCompress.c
+++ b/examples/fileCompress.c
@@ -1,7 +1,7 @@
 /* LZ4file API example : compress a file
  * Modified from an example code by anjiahao
  *
- * This example will demonstrate how 
+ * This example will demonstrate how
  * to manipulate lz4 compressed files like
  * normal files */
 
@@ -41,6 +41,7 @@
     void* const buf = malloc(CHUNK_SIZE);
     if (!buf) {
         printf("error: memory allocation failed \n");
+        return 1;
     }
 
     /* Of course, you can also use prefsPtr to
diff --git a/examples/printVersion.c b/examples/print_version.c
similarity index 100%
rename from examples/printVersion.c
rename to examples/print_version.c
diff --git a/examples/HCStreaming_ringBuffer.c b/examples/streamingHC_ringBuffer.c
similarity index 100%
rename from examples/HCStreaming_ringBuffer.c
rename to examples/streamingHC_ringBuffer.c
diff --git a/lib/Makefile b/lib/Makefile
index 06503cb..c8ac4d8 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -1,6 +1,6 @@
 # ################################################################
 # LZ4 library - Makefile
-# Copyright (C) Yann Collet 2011-2020
+# Copyright (C) Yann Collet 2011-2023
 # All rights reserved.
 #
 # This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets
@@ -31,12 +31,12 @@
 #  - LZ4 source repository : https://github.com/lz4/lz4
 #  - LZ4 forum froup : https://groups.google.com/forum/#!forum/lz4c
 # ################################################################
-SED = sed
+SED ?= sed
 
 # Version numbers
-LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
-LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
-LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
+LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
+LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
+LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
 LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
 LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
 LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
@@ -47,13 +47,12 @@
 BUILD_STATIC:=yes
 
 CPPFLAGS+= -DXXH_NAMESPACE=LZ4_
-CPPFLAGS+= $(MOREFLAGS)
-CFLAGS  ?= -O3
+USERCFLAGS:= -O3 $(CFLAGS)
 DEBUGFLAGS:= -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow \
              -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
              -Wundef -Wpointer-arith -Wstrict-aliasing=1
-CFLAGS  += $(DEBUGFLAGS)
-FLAGS    = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
+CFLAGS   = $(DEBUGFLAGS) $(USERCFLAGS)
+ALLFLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
 
 SRCFILES := $(sort $(wildcard *.c))
 
@@ -65,12 +64,17 @@
 	SHARED_EXT = dylib
 	SHARED_EXT_MAJOR = $(LIBVER_MAJOR).$(SHARED_EXT)
 	SHARED_EXT_VER = $(LIBVER).$(SHARED_EXT)
-	SONAME_FLAGS = -install_name $(libdir)/liblz4.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER)
+	SONAME_FLAGS = -install_name $(libdir)/liblz4.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER) -dynamiclib
 else
-	SONAME_FLAGS = -Wl,-soname=liblz4.$(SHARED_EXT).$(LIBVER_MAJOR)
-	SHARED_EXT = so
-	SHARED_EXT_MAJOR = $(SHARED_EXT).$(LIBVER_MAJOR)
-	SHARED_EXT_VER = $(SHARED_EXT).$(LIBVER)
+	ifeq ($(WINBASED),yes)
+		SHARED_EXT = dll
+		SHARED_EXT_VER = $(SHARED_EXT)
+	else  # posix non-mac
+		SONAME_FLAGS = -Wl,-soname=liblz4.$(SHARED_EXT).$(LIBVER_MAJOR)
+		SHARED_EXT = so
+		SHARED_EXT_MAJOR = $(SHARED_EXT).$(LIBVER_MAJOR)
+		SHARED_EXT_VER = $(SHARED_EXT).$(LIBVER)
+	endif
 endif
 
 .PHONY: default
@@ -79,19 +83,21 @@
 # silent mode by default; verbose can be triggered by V=1 or VERBOSE=1
 $(V)$(VERBOSE).SILENT:
 
+.PHONY:lib-release
 lib-release: DEBUGFLAGS :=
-lib-release: lib
+lib-release: lib liblz4.pc
 
 .PHONY: lib
 lib: liblz4.a liblz4
 
 .PHONY: all
-all: lib
+all: lib liblz4.pc
 
 .PHONY: all32
 all32: CFLAGS+=-m32
 all32: all
 
+CLEAN += liblz4.a
 liblz4.a: $(SRCFILES)
 ifeq ($(BUILD_STATIC),yes)  # can be disabled on command line
 	@echo compiling static library
@@ -100,9 +106,11 @@
 endif
 
 ifeq ($(WINBASED),yes)
+
+CLEAN += $(liblz4-dll.rc)
 liblz4-dll.rc: liblz4-dll.rc.in
 	@echo creating library resource
-	$(SED) -e 's|@LIBLZ4@|$(LIBLZ4)|' \
+	$(SED) -e 's|@LIBLZ4@|$(LIBLZ4_NAME)|' \
          -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
          -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
          -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
@@ -111,31 +119,47 @@
 liblz4-dll.o: liblz4-dll.rc
 	$(WINDRES) -i liblz4-dll.rc -o liblz4-dll.o
 
+CLEAN += $(LIBLZ4_EXP)
 $(LIBLZ4): $(SRCFILES) liblz4-dll.o
+  ifeq ($(BUILD_SHARED),yes)
 	@echo compiling dynamic library $(LIBVER)
-	$(CC) $(FLAGS) -DLZ4_DLL_EXPORT=1 -shared $^ -o dll/$@.dll -Wl,--out-implib,dll/$(LIBLZ4_EXP)
+	$(CC) $(ALLFLAGS) -DLZ4_DLL_EXPORT=1 -shared $^ -o $@ -Wl,--out-implib,$(LIBLZ4_EXP)
+  endif
 
 else   # not windows
 
 $(LIBLZ4): $(SRCFILES)
+  ifeq ($(BUILD_SHARED),yes)
 	@echo compiling dynamic library $(LIBVER)
-	$(CC) $(FLAGS) -shared $^ -fPIC -fvisibility=hidden $(SONAME_FLAGS) -o $@
+	$(CC) $(ALLFLAGS) -shared $^ -fPIC -fvisibility=hidden $(SONAME_FLAGS) -o $@
 	@echo creating versioned links
 	$(LN_SF) $@ liblz4.$(SHARED_EXT_MAJOR)
 	$(LN_SF) $@ liblz4.$(SHARED_EXT)
+  endif
 
 endif
+CLEAN += $(LIBLZ4)
 
 .PHONY: liblz4
 liblz4: $(LIBLZ4)
 
+CLEAN += liblz4.pc
+liblz4.pc: liblz4.pc.in Makefile
+	@echo creating pkgconfig
+	$(SED) -e 's|@PREFIX@|$(prefix)|' \
+           -e 's|@LIBDIR@|$(libdir)|' \
+           -e 's|@INCLUDEDIR@|$(includedir)|' \
+           -e 's|@VERSION@|$(LIBVER)|' \
+           -e 's|=${prefix}/|=$${prefix}/|' \
+           $< >$@
+
 .PHONY: clean
 clean:
 ifeq ($(WINBASED),yes)
 	$(RM) *.rc
 endif
-	$(RM) core *.o liblz4.pc dll/$(LIBLZ4).dll dll/$(LIBLZ4_EXP)
-	$(RM) *.a *.$(SHARED_EXT) *.$(SHARED_EXT_MAJOR) *.$(SHARED_EXT_VER)
+	$(RM) $(CLEAN) core *.o *.a
+	$(RM) *.$(SHARED_EXT) *.$(SHARED_EXT_MAJOR) *.$(SHARED_EXT_VER)
 	@echo Cleaning library completed
 
 #-----------------------------------------------------------------------------
@@ -169,30 +193,23 @@
   endif
 pkgconfigdir ?= $(PKGCONFIGDIR)
 
-liblz4.pc: liblz4.pc.in Makefile
-	@echo creating pkgconfig
-	$(SED) -e 's|@PREFIX@|$(prefix)|' \
-         -e 's|@LIBDIR@|$(libdir)|' \
-         -e 's|@INCLUDEDIR@|$(includedir)|' \
-         -e 's|@VERSION@|$(LIBVER)|' \
-         -e 's|=${prefix}/|=$${prefix}/|' \
-          $< >$@
-
+.PHONY: install
 install: lib liblz4.pc
-	$(INSTALL_DIR) $(DESTDIR)$(pkgconfigdir)/ $(DESTDIR)$(includedir)/ $(DESTDIR)$(libdir)/ $(DESTDIR)$(bindir)/
+	$(MAKE_DIR) $(DESTDIR)$(pkgconfigdir)/ $(DESTDIR)$(includedir)/ $(DESTDIR)$(libdir)/ $(DESTDIR)$(bindir)/
 	$(INSTALL_DATA) liblz4.pc $(DESTDIR)$(pkgconfigdir)/
 	@echo Installing libraries in $(DESTDIR)$(libdir)
   ifeq ($(BUILD_STATIC),yes)
 	$(INSTALL_DATA) liblz4.a $(DESTDIR)$(libdir)/liblz4.a
 	$(INSTALL_DATA) lz4frame_static.h $(DESTDIR)$(includedir)/lz4frame_static.h
+	$(INSTALL_DATA) lz4file.h $(DESTDIR)$(includedir)/lz4file.h
   endif
   ifeq ($(BUILD_SHARED),yes)
 # Traditionally, one installs the DLLs in the bin directory as programs
 # search them first in their directory. This allows to not pollute system
 # directories (like c:/windows/system32), nor modify the PATH variable.
     ifeq ($(WINBASED),yes)
-	$(INSTALL_PROGRAM) dll/$(LIBLZ4).dll $(DESTDIR)$(bindir)
-	$(INSTALL_PROGRAM) dll/$(LIBLZ4_EXP) $(DESTDIR)$(libdir)
+	$(INSTALL_PROGRAM) $(LIBLZ4) $(DESTDIR)$(bindir)
+	$(INSTALL_PROGRAM) $(LIBLZ4_EXP) $(DESTDIR)$(libdir)
     else
 	$(INSTALL_PROGRAM) liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(libdir)
 	$(LN_SF) liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(libdir)/liblz4.$(SHARED_EXT_MAJOR)
@@ -205,10 +222,11 @@
 	$(INSTALL_DATA) lz4frame.h $(DESTDIR)$(includedir)/lz4frame.h
 	@echo lz4 libraries installed
 
+.PHONY: uninstall
 uninstall:
 	$(RM) $(DESTDIR)$(pkgconfigdir)/liblz4.pc
-  ifeq (WINBASED,1)
-	$(RM) $(DESTDIR)$(bindir)/$(LIBLZ4).dll
+  ifeq (WINBASED,yes)
+	$(RM) $(DESTDIR)$(bindir)/$(LIBLZ4)
 	$(RM) $(DESTDIR)$(libdir)/$(LIBLZ4_EXP)
   else
 	$(RM) $(DESTDIR)$(libdir)/liblz4.$(SHARED_EXT)
@@ -220,6 +238,7 @@
 	$(RM) $(DESTDIR)$(includedir)/lz4hc.h
 	$(RM) $(DESTDIR)$(includedir)/lz4frame.h
 	$(RM) $(DESTDIR)$(includedir)/lz4frame_static.h
+	$(RM) $(DESTDIR)$(includedir)/lz4file.h
 	@echo lz4 libraries successfully uninstalled
 
 endif
diff --git a/lib/README.md b/lib/README.md
index 08d1cef..9039da3 100644
--- a/lib/README.md
+++ b/lib/README.md
@@ -100,7 +100,7 @@
   passed as argument to become a compression state is suitably aligned.
   This test can be disabled if it proves flaky, by setting this value to 0.
 
-- `LZ4_USER_MEMORY_FUNCTIONS` : replace calls to `<stdlib,h>`'s `malloc()`, `calloc()` and `free()`
+- `LZ4_USER_MEMORY_FUNCTIONS` : replace calls to `<stdlib.h>`'s `malloc()`, `calloc()` and `free()`
   by user-defined functions, which must be named `LZ4_malloc()`, `LZ4_calloc()` and `LZ4_free()`.
   User functions must be available at link time.
 
@@ -108,6 +108,12 @@
   Remove support of dynamic memory allocation.
   For more details, see description of this macro in `lib/lz4.c`.
 
+- `LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT` : experimental feature aimed at producing the same
+  compressed output on platforms of different endianness (i.e. little-endian and big-endian).
+  Output on little-endian platforms shall remain unchanged, while big-endian platforms will start producing
+  the same output as little-endian ones. This isn't expected to impact backward- and forward-compatibility
+  in any way.
+
 - `LZ4_FREESTANDING` : by setting this build macro to 1,
   LZ4/HC removes dependencies on the C standard library,
   including allocation functions and `memmove()`, `memcpy()`, and `memset()`.
@@ -115,6 +121,24 @@
   (embedded, bootloader, etc).
   For more details, see description of this macro in `lib/lz4.h`.
 
+- `LZ4_HEAPMODE` : Select how stateless compression functions like `LZ4_compress_default()`
+  allocate memory for their hash table,
+  in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
+
+- `LZ4HC_HEAPMODE` :  Select how stateless HC compression functions like `LZ4_compress_HC()`
+  allocate memory for their workspace:
+  in stack (0), or in heap (1:default).
+  Since workspace is rather large, stack can be inconvenient, hence heap mode is recommended.
+
+- `LZ4F_HEAPMODE` : selects how `LZ4F_compressFrame()` allocates the compression state,
+  either on stack (default, value 0) or using heap memory (value 1).
+
+
+#### Makefile variables
+
+The following `Makefile` variables can be selected to alter the profile of produced binaries :
+- `BUILD_SHARED` : generate `liblz4` dynamic library (enabled by default)
+- `BUILD_STATIC` : generate `liblz4` static library (enabled by default)
 
 
 #### Amalgamation
diff --git a/lib/lz4.c b/lib/lz4.c
index 654bfdf..a2f7abe 100644
--- a/lib/lz4.c
+++ b/lib/lz4.c
@@ -1,6 +1,6 @@
 /*
    LZ4 - Fast LZ compression algorithm
-   Copyright (C) 2011-2020, Yann Collet.
+   Copyright (C) 2011-2023, Yann Collet.
 
    BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
 
@@ -37,7 +37,8 @@
 **************************************/
 /*
  * LZ4_HEAPMODE :
- * Select how default compression functions will allocate memory for their hash table,
+ * Select how stateless compression functions like `LZ4_compress_default()`
+ * allocate memory for their hash table,
  * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
  */
 #ifndef LZ4_HEAPMODE
@@ -78,7 +79,7 @@
   ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
   || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
 #    define LZ4_FORCE_MEMORY_ACCESS 2
-#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
+#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) || defined(_MSC_VER)
 #    define LZ4_FORCE_MEMORY_ACCESS 1
 #  endif
 #endif
@@ -105,15 +106,13 @@
 #  define LZ4_SRC_INCLUDED 1
 #endif
 
-#ifndef LZ4_STATIC_LINKING_ONLY
-#define LZ4_STATIC_LINKING_ONLY
-#endif
-
 #ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
-#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
+#  define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
 #endif
 
-#define LZ4_STATIC_LINKING_ONLY  /* LZ4_DISTANCE_MAX */
+#ifndef LZ4_STATIC_LINKING_ONLY
+#  define LZ4_STATIC_LINKING_ONLY
+#endif
 #include "lz4.h"
 /* see also "memory routines" below */
 
@@ -125,14 +124,17 @@
 #  include <intrin.h>               /* only present in VS2005+ */
 #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
 #  pragma warning(disable : 6237)   /* disable: C6237: conditional expression is always 0 */
+#  pragma warning(disable : 6239)   /* disable: C6239: (<non-zero constant> && <expression>) always evaluates to the result of <expression> */
+#  pragma warning(disable : 6240)   /* disable: C6240: (<expression> && <non-zero constant>) always evaluates to the result of <expression> */
+#  pragma warning(disable : 6326)   /* disable: C6326: Potential comparison of a constant with another constant */
 #endif  /* _MSC_VER */
 
 #ifndef LZ4_FORCE_INLINE
-#  ifdef _MSC_VER    /* Visual Studio */
+#  if defined (_MSC_VER) && !defined (__clang__)    /* MSVC */
 #    define LZ4_FORCE_INLINE static __forceinline
 #  else
 #    if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
-#      ifdef __GNUC__
+#      if defined (__GNUC__) || defined (__clang__)
 #        define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
 #      else
 #        define LZ4_FORCE_INLINE static inline
@@ -279,7 +281,7 @@
    static int g_debuglog_enable = 1;
 #  define DEBUGLOG(l, ...) {                          \
         if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
-            fprintf(stderr, __FILE__ ": ");           \
+            fprintf(stderr, __FILE__  " %i: ", __LINE__); \
             fprintf(stderr, __VA_ARGS__);             \
             fprintf(stderr, " \n");                   \
     }   }
@@ -364,6 +366,11 @@
     return one.c[0];
 }
 
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+#define LZ4_PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__))
+#elif defined(_MSC_VER)
+#define LZ4_PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
+#endif
 
 #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
 /* lie to the compiler about data alignment; use with caution */
@@ -379,14 +386,16 @@
 
 /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
 /* currently only defined for gcc and icc */
-typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) LZ4_unalign;
+LZ4_PACK(typedef struct { U16 u16; }) LZ4_unalign16;
+LZ4_PACK(typedef struct { U32 u32; }) LZ4_unalign32;
+LZ4_PACK(typedef struct { reg_t uArch; }) LZ4_unalignST;
 
-static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign*)ptr)->u16; }
-static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign*)ptr)->u32; }
-static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalign*)ptr)->uArch; }
+static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign16*)ptr)->u16; }
+static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign32*)ptr)->u32; }
+static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalignST*)ptr)->uArch; }
 
-static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign*)memPtr)->u16 = value; }
-static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign*)memPtr)->u32 = value; }
+static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign16*)memPtr)->u16 = value; }
+static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign32*)memPtr)->u32 = value; }
 
 #else  /* safe and portable access using memcpy() */
 
@@ -424,10 +433,22 @@
         return LZ4_read16(memPtr);
     } else {
         const BYTE* p = (const BYTE*)memPtr;
-        return (U16)((U16)p[0] + (p[1]<<8));
+        return (U16)((U16)p[0] | (p[1]<<8));
     }
 }
 
+#ifdef LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT
+static U32 LZ4_readLE32(const void* memPtr)
+{
+    if (LZ4_isLittleEndian()) {
+        return LZ4_read32(memPtr);
+    } else {
+        const BYTE* p = (const BYTE*)memPtr;
+        return (U32)p[0] | (p[1]<<8) | (p[2]<<16) | (p[3]<<24);
+    }
+}
+#endif
+
 static void LZ4_writeLE16(void* memPtr, U16 value)
 {
     if (LZ4_isLittleEndian()) {
@@ -509,7 +530,7 @@
 
 /* LZ4_memcpy_using_offset()  presumes :
  * - dstEnd >= dstPtr + MINMATCH
- * - there is at least 8 bytes available to write after dstEnd */
+ * - there is at least 12 bytes available to write after dstEnd */
 LZ4_FORCE_INLINE void
 LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
 {
@@ -524,12 +545,12 @@
     case 2:
         LZ4_memcpy(v, srcPtr, 2);
         LZ4_memcpy(&v[2], srcPtr, 2);
-#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
+#if defined(_MSC_VER) && (_MSC_VER <= 1937) /* MSVC 2022 ver 17.7 or earlier */
 #  pragma warning(push)
 #  pragma warning(disable : 6385) /* warning C6385: Reading invalid data from 'v'. */
 #endif
         LZ4_memcpy(&v[4], v, 4);
-#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
+#if defined(_MSC_VER) && (_MSC_VER <= 1937) /* MSVC 2022 ver 17.7 or earlier */
 #  pragma warning(pop)
 #endif
         break;
@@ -776,7 +797,12 @@
 LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
 {
     if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
+
+#ifdef LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT
+    return LZ4_hash4(LZ4_readLE32(p), tableType);
+#else
     return LZ4_hash4(LZ4_read32(p), tableType);
+#endif
 }
 
 LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType)
@@ -803,23 +829,19 @@
     }
 }
 
+/* LZ4_putPosition*() : only used in byPtr mode */
 LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h,
-                                  void* tableBase, tableType_t const tableType,
-                            const BYTE* srcBase)
+                                  void* tableBase, tableType_t const tableType)
 {
-    switch (tableType)
-    {
-    case clearedTable: { /* illegal! */ assert(0); return; }
-    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
-    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
-    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
-    }
+    const BYTE** const hashTable = (const BYTE**)tableBase;
+    assert(tableType == byPtr); (void)tableType;
+    hashTable[h] = p;
 }
 
-LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
+LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType)
 {
     U32 const h = LZ4_hashPosition(p, tableType);
-    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
+    LZ4_putPositionOnHash(p, h, tableBase, tableType);
 }
 
 /* LZ4_getIndexOnHash() :
@@ -844,20 +866,18 @@
     assert(0); return 0;  /* forbidden case */
 }
 
-static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
+static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType)
 {
-    if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
-    if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
-    { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */
+    assert(tableType == byPtr); (void)tableType;
+    { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
 }
 
 LZ4_FORCE_INLINE const BYTE*
 LZ4_getPosition(const BYTE* p,
-                const void* tableBase, tableType_t tableType,
-                const BYTE* srcBase)
+                const void* tableBase, tableType_t tableType)
 {
     U32 const h = LZ4_hashPosition(p, tableType);
-    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
+    return LZ4_getPositionOnHash(h, tableBase, tableType);
 }
 
 LZ4_FORCE_INLINE void
@@ -901,9 +921,9 @@
     cctx->dictSize = 0;
 }
 
-/** LZ4_compress_generic() :
+/** LZ4_compress_generic_validated() :
  *  inlined, to ensure branches are decided at compilation time.
- *  Presumed already validated at this stage:
+ *  The following conditions are presumed already validated:
  *  - source != NULL
  *  - inputSize > 0
  */
@@ -921,10 +941,10 @@
                  const int acceleration)
 {
     int result;
-    const BYTE* ip = (const BYTE*) source;
+    const BYTE* ip = (const BYTE*)source;
 
     U32 const startIndex = cctx->currentOffset;
-    const BYTE* base = (const BYTE*) source - startIndex;
+    const BYTE* base = (const BYTE*)source - startIndex;
     const BYTE* lowLimit;
 
     const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
@@ -932,7 +952,8 @@
         dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
     const U32 dictSize =
         dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
-    const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with index in current context */
+    const U32 dictDelta =
+        (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with indexes in current context */
 
     int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
     U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */
@@ -957,11 +978,11 @@
 
     DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType);
     assert(ip != NULL);
+    if (tableType == byU16) assert(inputSize<LZ4_64Klimit);  /* Size too large (not within 64K limit) */
+    if (tableType == byPtr) assert(dictDirective==noDict);   /* only supported use case with byPtr */
     /* If init conditions are not met, we don't have to mark stream
      * as having dirty context, since no action was taken yet */
     if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */
-    if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) { return 0; }  /* Size too large (not within 64K limit) */
-    if (tableType==byPtr) assert(dictDirective==noDict);      /* only supported use case with byPtr */
     assert(acceleration >= 1);
 
     lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
@@ -981,7 +1002,12 @@
     if (inputSize<LZ4_minLength) goto _last_literals;        /* Input too small, no compression (all literals) */
 
     /* First Byte */
-    LZ4_putPosition(ip, cctx->hashTable, tableType, base);
+    {   U32 const h = LZ4_hashPosition(ip, tableType);
+        if (tableType == byPtr) {
+            LZ4_putPositionOnHash(ip, h, cctx->hashTable, byPtr);
+        } else {
+            LZ4_putIndexOnHash(startIndex, h, cctx->hashTable, tableType);
+    }   }
     ip++; forwardH = LZ4_hashPosition(ip, tableType);
 
     /* Main Loop */
@@ -1004,9 +1030,9 @@
                 if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
                 assert(ip < mflimitPlusOne);
 
-                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
+                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType);
                 forwardH = LZ4_hashPosition(forwardIp, tableType);
-                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
+                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType);
 
             } while ( (match+LZ4_DISTANCE_MAX < ip)
                    || (LZ4_read32(match) != LZ4_read32(ip)) );
@@ -1077,7 +1103,10 @@
 
         /* Catch up */
         filledIp = ip;
-        while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
+        assert(ip > anchor); /* this is always true as ip has been advanced before entering the main loop */
+        if ((match > lowLimit) && unlikely(ip[-1] == match[-1])) {
+            do { ip--; match--; } while (((ip > anchor) & (match > lowLimit)) && (unlikely(ip[-1] == match[-1])));
+        }
 
         /* Encode Literals */
         {   unsigned const litLength = (unsigned)(ip - anchor);
@@ -1092,7 +1121,7 @@
                 goto _last_literals;
             }
             if (litLength >= RUN_MASK) {
-                int len = (int)(litLength - RUN_MASK);
+                unsigned len = litLength - RUN_MASK;
                 *token = (RUN_MASK<<ML_BITS);
                 for(; len >= 255 ; len-=255) *op++ = 255;
                 *op++ = (BYTE)len;
@@ -1204,13 +1233,19 @@
         if (ip >= mflimitPlusOne) break;
 
         /* Fill table */
-        LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
+        {   U32 const h = LZ4_hashPosition(ip-2, tableType);
+            if (tableType == byPtr) {
+                LZ4_putPositionOnHash(ip-2, h, cctx->hashTable, byPtr);
+            } else {
+                U32 const idx = (U32)((ip-2) - base);
+                LZ4_putIndexOnHash(idx, h, cctx->hashTable, tableType);
+        }   }
 
         /* Test next position */
         if (tableType == byPtr) {
 
-            match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
-            LZ4_putPosition(ip, cctx->hashTable, tableType, base);
+            match = LZ4_getPosition(ip, cctx->hashTable, tableType);
+            LZ4_putPosition(ip, cctx->hashTable, tableType);
             if ( (match+LZ4_DISTANCE_MAX >= ip)
               && (LZ4_read32(match) == LZ4_read32(ip)) )
             { token=op++; *token=0; goto _next_match; }
@@ -1224,6 +1259,7 @@
             if (dictDirective == usingDictCtx) {
                 if (matchIndex < startIndex) {
                     /* there was no match, try the dictionary */
+                    assert(tableType == byU32);
                     matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
                     match = dictBase + matchIndex;
                     lowLimit = dictionary;   /* required for match length counter */
@@ -1377,9 +1413,10 @@
  */
 int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
 {
-    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
+    LZ4_stream_t_internal* const ctx = &((LZ4_stream_t*)state)->internal_donotuse;
     if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
     if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
+    assert(ctx != NULL);
 
     if (dstCapacity >= LZ4_compressBound(srcSize)) {
         if (srcSize < LZ4_64Klimit) {
@@ -1413,17 +1450,17 @@
 }
 
 
-int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+int LZ4_compress_fast(const char* src, char* dest, int srcSize, int dstCapacity, int acceleration)
 {
     int result;
 #if (LZ4_HEAPMODE)
-    LZ4_stream_t* ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
+    LZ4_stream_t* const ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
     if (ctxPtr == NULL) return 0;
 #else
     LZ4_stream_t ctx;
     LZ4_stream_t* const ctxPtr = &ctx;
 #endif
-    result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
+    result = LZ4_compress_fast_extState(ctxPtr, src, dest, srcSize, dstCapacity, acceleration);
 
 #if (LZ4_HEAPMODE)
     FREEMEM(ctxPtr);
@@ -1432,43 +1469,51 @@
 }
 
 
-int LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize)
+int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity)
 {
-    return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);
+    return LZ4_compress_fast(src, dst, srcSize, dstCapacity, 1);
 }
 
 
 /* Note!: This function leaves the stream in an unclean/broken state!
  * It is not safe to subsequently use the same state with a _fastReset() or
  * _continue() call without resetting it. */
-static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+static int LZ4_compress_destSize_extState_internal(LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration)
 {
     void* const s = LZ4_initStream(state, sizeof (*state));
     assert(s != NULL); (void)s;
 
     if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */
-        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
+        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, acceleration);
     } else {
         if (*srcSizePtr < LZ4_64Klimit) {
-            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
+            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, acceleration);
         } else {
             tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
-            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
+            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, acceleration);
     }   }
 }
 
+int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration)
+{
+    int const r = LZ4_compress_destSize_extState_internal((LZ4_stream_t*)state, src, dst, srcSizePtr, targetDstSize, acceleration);
+    /* clean the state on exit */
+    LZ4_initStream(state, sizeof (LZ4_stream_t));
+    return r;
+}
+
 
 int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
 {
 #if (LZ4_HEAPMODE)
-    LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
+    LZ4_stream_t* const ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
     if (ctx == NULL) return 0;
 #else
     LZ4_stream_t ctxBody;
-    LZ4_stream_t* ctx = &ctxBody;
+    LZ4_stream_t* const ctx = &ctxBody;
 #endif
 
-    int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
+    int result = LZ4_compress_destSize_extState_internal(ctx, src, dst, srcSizePtr, targetDstSize, 1);
 
 #if (LZ4_HEAPMODE)
     FREEMEM(ctx);
@@ -1537,14 +1582,17 @@
 #endif
 
 
+typedef enum { _ld_fast, _ld_slow } LoadDict_mode_e;
 #define HASH_UNIT sizeof(reg_t)
-int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
+int LZ4_loadDict_internal(LZ4_stream_t* LZ4_dict,
+                    const char* dictionary, int dictSize,
+                    LoadDict_mode_e _ld)
 {
-    LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
+    LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
     const tableType_t tableType = byU32;
     const BYTE* p = (const BYTE*)dictionary;
     const BYTE* const dictEnd = p + dictSize;
-    const BYTE* base;
+    U32 idx32;
 
     DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
 
@@ -1567,19 +1615,46 @@
     }
 
     if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
-    base = dictEnd - dict->currentOffset;
     dict->dictionary = p;
     dict->dictSize = (U32)(dictEnd - p);
     dict->tableType = (U32)tableType;
+    idx32 = dict->currentOffset - dict->dictSize;
 
     while (p <= dictEnd-HASH_UNIT) {
-        LZ4_putPosition(p, dict->hashTable, tableType, base);
-        p+=3;
+        U32 const h = LZ4_hashPosition(p, tableType);
+        /* Note: overwriting => favors positions end of dictionary */
+        LZ4_putIndexOnHash(idx32, h, dict->hashTable, tableType);
+        p+=3; idx32+=3;
+    }
+
+    if (_ld == _ld_slow) {
+        /* Fill hash table with additional references, to improve compression capability */
+        p = dict->dictionary;
+        idx32 = dict->currentOffset - dict->dictSize;
+        while (p <= dictEnd-HASH_UNIT) {
+            U32 const h = LZ4_hashPosition(p, tableType);
+            U32 const limit = dict->currentOffset - 64 KB;
+            if (LZ4_getIndexOnHash(h, dict->hashTable, tableType) <= limit) {
+                /* Note: not overwriting => favors positions beginning of dictionary */
+                LZ4_putIndexOnHash(idx32, h, dict->hashTable, tableType);
+            }
+            p++; idx32++;
+        }
     }
 
     return (int)dict->dictSize;
 }
 
+int LZ4_loadDict(LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
+{
+    return LZ4_loadDict_internal(LZ4_dict, dictionary, dictSize, _ld_fast);
+}
+
+int LZ4_loadDictSlow(LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
+{
+    return LZ4_loadDict_internal(LZ4_dict, dictionary, dictSize, _ld_slow);
+}
+
 void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream)
 {
     const LZ4_stream_t_internal* dictCtx = (dictionaryStream == NULL) ? NULL :
@@ -1711,7 +1786,7 @@
 /* Hidden debug function, to force-test external dictionary mode */
 int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
 {
-    LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
+    LZ4_stream_t_internal* const streamPtr = &LZ4_dict->internal_donotuse;
     int result;
 
     LZ4_renormDictT(streamPtr, srcSize);
@@ -1774,7 +1849,7 @@
  * does not know end of input
  * presumes input is well formed
  * note : will consume at least one byte */
-size_t read_long_length_no_check(const BYTE** pp)
+static size_t read_long_length_no_check(const BYTE** pp)
 {
     size_t b, l = 0;
     do { b = **pp; (*pp)++; l += b; } while (b==255);
@@ -1911,6 +1986,17 @@
     if (initial_check && unlikely((*ip) >= ilimit)) {    /* read limit reached */
         return rvl_error;
     }
+    s = **ip;
+    (*ip)++;
+    length += s;
+    if (unlikely((*ip) > ilimit)) {    /* read limit reached */
+        return rvl_error;
+    }
+    /* accumulator overflow detection (32-bit mode only) */
+    if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
+        return rvl_error;
+    }
+    if (likely(s != 255)) return length;
     do {
         s = **ip;
         (*ip)++;
@@ -1919,10 +2005,10 @@
             return rvl_error;
         }
         /* accumulator overflow detection (32-bit mode only) */
-        if ((sizeof(length)<8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
+        if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
             return rvl_error;
         }
-    } while (s==255);
+    } while (s == 255);
 
     return length;
 }
@@ -1988,63 +2074,73 @@
      * note : fast loop may show a regression for some client arm chips. */
 #if LZ4_FAST_DEC_LOOP
         if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {
-            DEBUGLOG(6, "skip fast decode loop");
+            DEBUGLOG(6, "move to safe decode loop");
             goto safe_decode;
         }
 
         /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */
+        DEBUGLOG(6, "using fast decode loop");
         while (1) {
             /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
             assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
             assert(ip < iend);
             token = *ip++;
             length = token >> ML_BITS;  /* literal length */
+            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
 
             /* decode literal length */
             if (length == RUN_MASK) {
                 size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1);
-                if (addl == rvl_error) { goto _output_error; }
+                if (addl == rvl_error) {
+                    DEBUGLOG(6, "error reading long literal length");
+                    goto _output_error;
+                }
                 length += addl;
                 if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
                 if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
 
                 /* copy literals */
-                cpy = op+length;
                 LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
-                if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
-                LZ4_wildCopy32(op, ip, cpy);
-                ip += length; op = cpy;
-            } else {
-                cpy = op+length;
-                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
+                if ((op+length>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
+                LZ4_wildCopy32(op, ip, op+length);
+                ip += length; op += length;
+            } else if (ip <= iend-(16 + 1/*max lit + offset + nextToken*/)) {
                 /* We don't need to check oend, since we check it once for each loop below */
-                if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }
+                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
                 /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */
                 LZ4_memcpy(op, ip, 16);
-                ip += length; op = cpy;
+                ip += length; op += length;
+            } else {
+                goto safe_literal_copy;
             }
 
             /* get offset */
             offset = LZ4_readLE16(ip); ip+=2;
+            DEBUGLOG(6, "blockPos%6u: offset = %u", (unsigned)(op-(BYTE*)dst), (unsigned)offset);
             match = op - offset;
             assert(match <= op);  /* overflow check */
 
             /* get matchlength */
             length = token & ML_MASK;
+            DEBUGLOG(7, "  match length token = %u (len==%u)", (unsigned)length, (unsigned)length+MINMATCH);
 
             if (length == ML_MASK) {
                 size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
-                if (addl == rvl_error) { goto _output_error; }
+                if (addl == rvl_error) {
+                    DEBUGLOG(5, "error reading long match length");
+                    goto _output_error;
+                }
                 length += addl;
                 length += MINMATCH;
+                DEBUGLOG(7, "  long match length == %u", (unsigned)length);
                 if (unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */
-                if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
                 if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
                     goto safe_match_copy;
                 }
             } else {
                 length += MINMATCH;
                 if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
+                    DEBUGLOG(7, "moving to safe_match_copy (ml==%u)", (unsigned)length);
                     goto safe_match_copy;
                 }
 
@@ -2062,7 +2158,10 @@
                         continue;
             }   }   }
 
-            if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
+            if ( checkOffset && (unlikely(match + dictSize < lowPrefix)) ) {
+                DEBUGLOG(5, "Error : pos=%zi, offset=%zi => outside buffers", op-lowPrefix, op-match);
+                goto _output_error;
+            }
             /* match starting within external dictionary */
             if ((dict==usingExtDict) && (match < lowPrefix)) {
                 assert(dictEnd != NULL);
@@ -2071,7 +2170,8 @@
                         DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
                         length = MIN(length, (size_t)(oend-op));
                     } else {
-                        goto _output_error;  /* end-of-block condition violated */
+                        DEBUGLOG(6, "end-of-block condition violated")
+                        goto _output_error;
                 }   }
 
                 if (length <= (size_t)(lowPrefix-match)) {
@@ -2111,10 +2211,12 @@
 #endif
 
         /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
+        DEBUGLOG(6, "using safe decode loop");
         while (1) {
             assert(ip < iend);
             token = *ip++;
             length = token >> ML_BITS;  /* literal length */
+            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
 
             /* A two-stage shortcut for the most common case:
              * 1) If the literal length is 0..14, and there is enough space,
@@ -2135,6 +2237,7 @@
                 /* The second stage: prepare for match copying, decode full info.
                  * If it doesn't work out, the info won't be wasted. */
                 length = token & ML_MASK; /* match length */
+                DEBUGLOG(7, "blockPos%6u: matchLength token = %u (len=%u)", (unsigned)(op-(BYTE*)dst), (unsigned)length, (unsigned)length + 4);
                 offset = LZ4_readLE16(ip); ip += 2;
                 match = op - offset;
                 assert(match <= op); /* check overflow */
@@ -2166,11 +2269,12 @@
                 if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
             }
 
-            /* copy literals */
-            cpy = op+length;
 #if LZ4_FAST_DEC_LOOP
         safe_literal_copy:
 #endif
+            /* copy literals */
+            cpy = op+length;
+
             LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
             if ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) {
                 /* We've either hit the input parsing restriction or the output parsing restriction.
@@ -2206,9 +2310,10 @@
                       * so check that we exactly consume the input and don't overrun the output buffer.
                       */
                     if ((ip+length != iend) || (cpy > oend)) {
-                        DEBUGLOG(6, "should have been last run of literals")
-                        DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);
-                        DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend);
+                        DEBUGLOG(5, "should have been last run of literals")
+                        DEBUGLOG(5, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);
+                        DEBUGLOG(5, "or cpy(%p) > (oend-MFLIMIT)(%p)", cpy, oend-MFLIMIT);
+                        DEBUGLOG(5, "after writing %u bytes / %i bytes available", (unsigned)(op-(BYTE*)dst), outputSize);
                         goto _output_error;
                     }
                 }
@@ -2234,6 +2339,7 @@
 
             /* get matchlength */
             length = token & ML_MASK;
+            DEBUGLOG(7, "blockPos%6u: matchLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
 
     _copy_match:
             if (length == ML_MASK) {
@@ -2323,7 +2429,7 @@
                 while (op < cpy) { *op++ = *match++; }
             } else {
                 LZ4_memcpy(op, match, 8);
-                if (length > 16)  { LZ4_wildCopy8(op+8, match+8, cpy); }
+                if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); }
             }
             op = cpy;   /* wildcopy correction */
         }
@@ -2418,6 +2524,7 @@
                                      int compressedSize, int maxOutputSize,
                                      const void* dictStart, size_t dictSize)
 {
+    DEBUGLOG(5, "LZ4_decompress_safe_forceExtDict");
     return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
                                   decode_full_block, usingExtDict,
                                   (BYTE*)dest, (const BYTE*)dictStart, dictSize);
diff --git a/lib/lz4.h b/lib/lz4.h
index 491c608..80e3e5c 100644
--- a/lib/lz4.h
+++ b/lib/lz4.h
@@ -1,7 +1,7 @@
 /*
  *  LZ4 - Fast LZ compression algorithm
  *  Header File
- *  Copyright (C) 2011-2020, Yann Collet.
+ *  Copyright (C) 2011-2023, Yann Collet.
 
    BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
 
@@ -129,8 +129,8 @@
 
 /*------   Version   ------*/
 #define LZ4_VERSION_MAJOR    1    /* for breaking interface changes  */
-#define LZ4_VERSION_MINOR    9    /* for new (non-breaking) interface capabilities */
-#define LZ4_VERSION_RELEASE  4    /* for tweaks, bug-fixes, or development */
+#define LZ4_VERSION_MINOR   10    /* for new (non-breaking) interface capabilities */
+#define LZ4_VERSION_RELEASE  0    /* for tweaks, bug-fixes, or development */
 
 #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
 
@@ -144,23 +144,25 @@
 
 
 /*-************************************
-*  Tuning parameter
+*  Tuning memory usage
 **************************************/
-#define LZ4_MEMORY_USAGE_MIN 10
-#define LZ4_MEMORY_USAGE_DEFAULT 14
-#define LZ4_MEMORY_USAGE_MAX 20
-
 /*!
  * LZ4_MEMORY_USAGE :
- * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; )
- * Increasing memory usage improves compression ratio, at the cost of speed.
+ * Can be selected at compile time, by setting LZ4_MEMORY_USAGE.
+ * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB)
+ * Increasing memory usage improves compression ratio, generally at the cost of speed.
  * Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality.
- * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
+ * Default value is 14, for 16KB, which nicely fits into most L1 caches.
  */
 #ifndef LZ4_MEMORY_USAGE
 # define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
 #endif
 
+/* These are absolute limits, they should not be changed by users */
+#define LZ4_MEMORY_USAGE_MIN 10
+#define LZ4_MEMORY_USAGE_DEFAULT 14
+#define LZ4_MEMORY_USAGE_MAX 20
+
 #if (LZ4_MEMORY_USAGE < LZ4_MEMORY_USAGE_MIN)
 #  error "LZ4_MEMORY_USAGE is too small !"
 #endif
@@ -189,8 +191,9 @@
 LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);
 
 /*! LZ4_decompress_safe() :
- *  compressedSize : is the exact complete size of the compressed block.
- *  dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size.
+ * @compressedSize : is the exact complete size of the compressed block.
+ * @dstCapacity : is the size of destination buffer (which must be already allocated),
+ *                presumed an upper bound of decompressed size.
  * @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
  *           If destination buffer is not large enough, decoding will stop and output an error code (negative value).
  *           If the source stream is detected malformed, the function will stop decoding and return a negative result.
@@ -242,20 +245,20 @@
 LZ4LIB_API int LZ4_sizeofState(void);
 LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
 
-
 /*! LZ4_compress_destSize() :
  *  Reverse the logic : compresses as much data as possible from 'src' buffer
- *  into already allocated buffer 'dst', of size >= 'targetDestSize'.
+ *  into already allocated buffer 'dst', of size >= 'dstCapacity'.
  *  This function either compresses the entire 'src' content into 'dst' if it's large enough,
  *  or fill 'dst' buffer completely with as much data as possible from 'src'.
  *  note: acceleration parameter is fixed to "default".
  *
- * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
+ * *srcSizePtr : in+out parameter. Initially contains size of input.
+ *               Will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
  *               New value is necessarily <= input value.
- * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
+ * @return : Nb bytes written into 'dst' (necessarily <= dstCapacity)
  *           or 0 if compression fails.
  *
- * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):
+ * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed in v1.9.2+):
  *        the produced compressed content could, in specific circumstances,
  *        require to be decompressed into a destination buffer larger
  *        by at least 1 byte than the content to decompress.
@@ -266,8 +269,7 @@
  *        a dstCapacity which is > decompressedSize, by at least 1 byte.
  *        See https://github.com/lz4/lz4/issues/859 for details
  */
-LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
-
+LZ4LIB_API int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize);
 
 /*! LZ4_decompress_safe_partial() :
  *  Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',
@@ -311,7 +313,7 @@
 ***********************************************/
 typedef union LZ4_stream_u LZ4_stream_t;  /* incomplete type (defined later) */
 
-/**
+/*!
  Note about RC_INVOKED
 
  - RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio).
@@ -361,13 +363,58 @@
  *  LZ4_loadDict() triggers a reset, so any previous data will be forgotten.
  *  The same dictionary will have to be loaded on decompression side for successful decoding.
  *  Dictionary are useful for better compression of small data (KB range).
- *  While LZ4 accept any input as dictionary,
- *  results are generally better when using Zstandard's Dictionary Builder.
+ *  While LZ4 itself accepts any input as dictionary, dictionary efficiency is also a topic.
+ *  When in doubt, employ the Zstandard's Dictionary Builder.
  *  Loading a size of 0 is allowed, and is the same as reset.
- * @return : loaded dictionary size, in bytes (necessarily <= 64 KB)
+ * @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
  */
 LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
 
+/*! LZ4_loadDictSlow() : v1.10.0+
+ *  Same as LZ4_loadDict(),
+ *  but uses a bit more cpu to reference the dictionary content more thoroughly.
+ *  This is expected to slightly improve compression ratio.
+ *  The extra-cpu cost is likely worth it if the dictionary is re-used across multiple sessions.
+ * @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
+ */
+LZ4LIB_API int LZ4_loadDictSlow(LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
+
+/*! LZ4_attach_dictionary() : stable since v1.10.0
+ *
+ *  This allows efficient re-use of a static dictionary multiple times.
+ *
+ *  Rather than re-loading the dictionary buffer into a working context before
+ *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
+ *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
+ *  in which the working stream references @dictionaryStream in-place.
+ *
+ *  Several assumptions are made about the state of @dictionaryStream.
+ *  Currently, only states which have been prepared by LZ4_loadDict() or
+ *  LZ4_loadDictSlow() should be expected to work.
+ *
+ *  Alternatively, the provided @dictionaryStream may be NULL,
+ *  in which case any existing dictionary stream is unset.
+ *
+ *  If a dictionary is provided, it replaces any pre-existing stream history.
+ *  The dictionary contents are the only history that can be referenced and
+ *  logically immediately precede the data compressed in the first subsequent
+ *  compression call.
+ *
+ *  The dictionary will only remain attached to the working stream through the
+ *  first compression call, at the end of which it is cleared.
+ * @dictionaryStream stream (and source buffer) must remain in-place / accessible / unchanged
+ *  through the completion of the compression session.
+ *
+ *  Note: there is no equivalent LZ4_attach_*() method on the decompression side
+ *  because there is no initialization cost, hence no need to share the cost across multiple sessions.
+ *  To decompress LZ4 blocks using dictionary, attached or not,
+ *  just employ the regular LZ4_setStreamDecode() for streaming,
+ *  or the stateless LZ4_decompress_safe_usingDict() for one-shot decompression.
+ */
+LZ4LIB_API void
+LZ4_attach_dictionary(LZ4_stream_t* workingStream,
+                const LZ4_stream_t* dictionaryStream);
+
 /*! LZ4_compress_fast_continue() :
  *  Compress 'src' content using data from previously compressed blocks, for better compression ratio.
  * 'dst' buffer must be already allocated.
@@ -443,11 +490,24 @@
 LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
 #define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize))  /* for static allocation; maxBlockSize presumed valid */
 
-/*! LZ4_decompress_*_continue() :
- *  These decoding functions allow decompression of consecutive blocks in "streaming" mode.
- *  A block is an unsplittable entity, it must be presented entirely to a decompression function.
- *  Decompression functions only accepts one block at a time.
- *  The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
+/*! LZ4_decompress_safe_continue() :
+ *  This decoding function allows decompression of consecutive blocks in "streaming" mode.
+ *  The difference with the usual independent blocks is that
+ *  new blocks are allowed to find references into former blocks.
+ *  A block is an unsplittable entity, and must be presented entirely to the decompression function.
+ *  LZ4_decompress_safe_continue() only accepts one block at a time.
+ *  It's modeled after `LZ4_decompress_safe()` and behaves similarly.
+ *
+ * @LZ4_streamDecode : decompression state, tracking the position in memory of past data
+ * @compressedSize : exact complete size of one compressed block.
+ * @dstCapacity : size of destination buffer (which must be already allocated),
+ *                must be an upper bound of decompressed size.
+ * @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
+ *           If destination buffer is not large enough, decoding will stop and output an error code (negative value).
+ *           If the source stream is detected malformed, the function will stop decoding and return a negative result.
+ *
+ *  The last 64KB of previously decoded data *must* remain available and unmodified
+ *  at the memory position where they were previously decoded.
  *  If less than 64KB of data has been decoded, all the data must be present.
  *
  *  Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
@@ -474,10 +534,10 @@
                         int srcSize, int dstCapacity);
 
 
-/*! LZ4_decompress_*_usingDict() :
- *  These decoding functions work the same as
- *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
- *  They are stand-alone, and don't need an LZ4_streamDecode_t structure.
+/*! LZ4_decompress_safe_usingDict() :
+ *  Works the same as
+ *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue()
+ *  However, it's stateless: it doesn't need any LZ4_streamDecode_t state.
  *  Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
  *  Performance tip : Decompression speed can be substantially increased
  *                    when dst == dictStart + dictSize.
@@ -487,6 +547,12 @@
                               int srcSize, int dstCapacity,
                               const char* dictStart, int dictSize);
 
+/*! LZ4_decompress_safe_partial_usingDict() :
+ *  Behaves the same as LZ4_decompress_safe_partial()
+ *  with the added ability to specify a memory segment for past data.
+ *  Performance tip : Decompression speed can be substantially increased
+ *                    when dst == dictStart + dictSize.
+ */
 LZ4LIB_API int
 LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
                                       int compressedSize,
@@ -526,9 +592,9 @@
 #define LZ4_STATIC_3504398509
 
 #ifdef LZ4_PUBLISH_STATIC_FUNCTIONS
-#define LZ4LIB_STATIC_API LZ4LIB_API
+# define LZ4LIB_STATIC_API LZ4LIB_API
 #else
-#define LZ4LIB_STATIC_API
+# define LZ4LIB_STATIC_API
 #endif
 
 
@@ -544,36 +610,11 @@
  */
 LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
 
-/*! LZ4_attach_dictionary() :
- *  This is an experimental API that allows
- *  efficient use of a static dictionary many times.
- *
- *  Rather than re-loading the dictionary buffer into a working context before
- *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
- *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
- *  in which the working stream references the dictionary stream in-place.
- *
- *  Several assumptions are made about the state of the dictionary stream.
- *  Currently, only streams which have been prepared by LZ4_loadDict() should
- *  be expected to work.
- *
- *  Alternatively, the provided dictionaryStream may be NULL,
- *  in which case any existing dictionary stream is unset.
- *
- *  If a dictionary is provided, it replaces any pre-existing stream history.
- *  The dictionary contents are the only history that can be referenced and
- *  logically immediately precede the data compressed in the first subsequent
- *  compression call.
- *
- *  The dictionary will only remain attached to the working stream through the
- *  first compression call, at the end of which it is cleared. The dictionary
- *  stream (and source buffer) must remain in-place / accessible / unchanged
- *  through the completion of the first compression call on the stream.
+/*! LZ4_compress_destSize_extState() : introduced in v1.10.0
+ *  Same as LZ4_compress_destSize(), but using an externally allocated state.
+ *  Also: exposes @acceleration
  */
-LZ4LIB_STATIC_API void
-LZ4_attach_dictionary(LZ4_stream_t* workingStream,
-                const LZ4_stream_t* dictionaryStream);
-
+int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration);
 
 /*! In-place compression and decompression
  *
@@ -685,7 +726,7 @@
     /* Implicit padding to ensure structure is aligned */
 };
 
-#define LZ4_STREAM_MINSIZE  ((1UL << LZ4_MEMORY_USAGE) + 32)  /* static size, for inter-version compatibility */
+#define LZ4_STREAM_MINSIZE  ((1UL << (LZ4_MEMORY_USAGE)) + 32)  /* static size, for inter-version compatibility */
 union LZ4_stream_u {
     char minStateSize[LZ4_STREAM_MINSIZE];
     LZ4_stream_t_internal internal_donotuse;
@@ -706,7 +747,7 @@
  *  Note2: An LZ4_stream_t structure guarantees correct alignment and size.
  *  Note3: Before v1.9.0, use LZ4_resetStream() instead
 **/
-LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);
+LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* stateBuffer, size_t size);
 
 
 /*! LZ4_streamDecode_t :
@@ -818,11 +859,12 @@
  *         But they may happen if input data is invalid (error or intentional tampering).
  *         As a consequence, use these functions in trusted environments with trusted data **only**.
  */
-LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
+LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial() instead")
 LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
-LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
+LZ4_DEPRECATED("This function is deprecated and unsafe. Consider migrating towards LZ4_decompress_safe_continue() instead. "
+               "Note that the contract will change (requires block's compressed size, instead of decompressed size)")
 LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
-LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
+LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial_usingDict() instead")
 LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
 
 /*! LZ4_resetStream() :
diff --git a/lib/lz4file.c b/lib/lz4file.c
index eaf9b17..a4197ea 100644
--- a/lib/lz4file.c
+++ b/lib/lz4file.c
@@ -31,11 +31,21 @@
  * - LZ4 homepage : http://www.lz4.org
  * - LZ4 source repository : https://github.com/lz4/lz4
  */
-#include <stdlib.h>
+#include <stdlib.h>  /* malloc, free */
 #include <string.h>
+#include <assert.h>
 #include "lz4.h"
 #include "lz4file.h"
 
+static LZ4F_errorCode_t returnErrorCode(LZ4F_errorCodes code)
+{
+    return (LZ4F_errorCode_t)-(ptrdiff_t)code;
+}
+#undef RETURN_ERROR
+#define RETURN_ERROR(e) return returnErrorCode(LZ4F_ERROR_ ## e)
+
+/* =====   read API   ===== */
+
 struct LZ4_readFile_s {
   LZ4F_dctx* dctxPtr;
   FILE* fp;
@@ -45,76 +55,80 @@
   size_t srcBufMaxSize;
 };
 
-struct LZ4_writeFile_s {
-  LZ4F_cctx* cctxPtr;
-  FILE* fp;
-  LZ4_byte* dstBuf;
-  size_t maxWriteSize;
-  size_t dstBufMaxSize;
-  LZ4F_errorCode_t errCode;
-};
+static void LZ4F_freeReadFile(LZ4_readFile_t* lz4fRead)
+{
+  if (lz4fRead==NULL) return;
+  LZ4F_freeDecompressionContext(lz4fRead->dctxPtr);
+  free(lz4fRead->srcBuf);
+  free(lz4fRead);
+}
+
+static void LZ4F_freeAndNullReadFile(LZ4_readFile_t** statePtr)
+{
+  assert(statePtr != NULL);
+  LZ4F_freeReadFile(*statePtr);
+  *statePtr = NULL;
+}
 
 LZ4F_errorCode_t LZ4F_readOpen(LZ4_readFile_t** lz4fRead, FILE* fp)
 {
   char buf[LZ4F_HEADER_SIZE_MAX];
   size_t consumedSize;
   LZ4F_errorCode_t ret;
-  LZ4F_frameInfo_t info;
 
   if (fp == NULL || lz4fRead == NULL) {
-    return -LZ4F_ERROR_GENERIC;
+    RETURN_ERROR(parameter_null);
   }
 
   *lz4fRead = (LZ4_readFile_t*)calloc(1, sizeof(LZ4_readFile_t));
   if (*lz4fRead == NULL) {
-    return -LZ4F_ERROR_allocation_failed;
+    RETURN_ERROR(allocation_failed);
   }
 
-  ret = LZ4F_createDecompressionContext(&(*lz4fRead)->dctxPtr, LZ4F_getVersion());
+  ret = LZ4F_createDecompressionContext(&(*lz4fRead)->dctxPtr, LZ4F_VERSION);
   if (LZ4F_isError(ret)) {
-    free(*lz4fRead);
+    LZ4F_freeAndNullReadFile(lz4fRead);
     return ret;
   }
 
   (*lz4fRead)->fp = fp;
   consumedSize = fread(buf, 1, sizeof(buf), (*lz4fRead)->fp);
   if (consumedSize != sizeof(buf)) {
-    free(*lz4fRead);
-    return -LZ4F_ERROR_GENERIC;
+    LZ4F_freeAndNullReadFile(lz4fRead);
+    RETURN_ERROR(io_read);
   }
 
-  ret = LZ4F_getFrameInfo((*lz4fRead)->dctxPtr, &info, buf, &consumedSize);
-  if (LZ4F_isError(ret)) {
-      LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
-      free(*lz4fRead);
-      return ret;
+  { LZ4F_frameInfo_t info;
+    LZ4F_errorCode_t const r = LZ4F_getFrameInfo((*lz4fRead)->dctxPtr, &info, buf, &consumedSize);
+    if (LZ4F_isError(r)) {
+      LZ4F_freeAndNullReadFile(lz4fRead);
+      return r;
     }
 
-  switch (info.blockSizeID) {
-    case LZ4F_default :
-    case LZ4F_max64KB :
-      (*lz4fRead)->srcBufMaxSize = 64 * 1024;
-      break;
-    case LZ4F_max256KB:
-      (*lz4fRead)->srcBufMaxSize = 256 * 1024;
-      break;
-    case LZ4F_max1MB:
-      (*lz4fRead)->srcBufMaxSize = 1 * 1024 * 1024;
-      break;
-    case LZ4F_max4MB:
-      (*lz4fRead)->srcBufMaxSize = 4 * 1024 * 1024;
-      break;
-    default:
-      LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
-      free(*lz4fRead);
-      return -LZ4F_ERROR_maxBlockSize_invalid;
+    switch (info.blockSizeID) {
+      case LZ4F_default :
+      case LZ4F_max64KB :
+        (*lz4fRead)->srcBufMaxSize = 64 * 1024;
+        break;
+      case LZ4F_max256KB:
+        (*lz4fRead)->srcBufMaxSize = 256 * 1024;
+        break;
+      case LZ4F_max1MB:
+        (*lz4fRead)->srcBufMaxSize = 1 * 1024 * 1024;
+        break;
+      case LZ4F_max4MB:
+        (*lz4fRead)->srcBufMaxSize = 4 * 1024 * 1024;
+        break;
+      default:
+        LZ4F_freeAndNullReadFile(lz4fRead);
+        RETURN_ERROR(maxBlockSize_invalid);
+    }
   }
 
   (*lz4fRead)->srcBuf = (LZ4_byte*)malloc((*lz4fRead)->srcBufMaxSize);
   if ((*lz4fRead)->srcBuf == NULL) {
-    LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
-    free(lz4fRead);
-    return -LZ4F_ERROR_allocation_failed;
+    LZ4F_freeAndNullReadFile(lz4fRead);
+    RETURN_ERROR(allocation_failed);
   }
 
   (*lz4fRead)->srcBufSize = sizeof(buf) - consumedSize;
@@ -129,7 +143,7 @@
   size_t next = 0;
 
   if (lz4fRead == NULL || buf == NULL)
-    return -LZ4F_ERROR_GENERIC;
+    RETURN_ERROR(parameter_null);
 
   while (next < size) {
     size_t srcsize = lz4fRead->srcBufSize - lz4fRead->srcBufNext;
@@ -142,12 +156,10 @@
         lz4fRead->srcBufSize = ret;
         srcsize = lz4fRead->srcBufSize;
         lz4fRead->srcBufNext = 0;
-      }
-      else if (ret == 0) {
+      } else if (ret == 0) {
         break;
-      }
-      else {
-        return -LZ4F_ERROR_GENERIC;
+      } else {
+        RETURN_ERROR(io_read);
       }
     }
 
@@ -171,24 +183,48 @@
 LZ4F_errorCode_t LZ4F_readClose(LZ4_readFile_t* lz4fRead)
 {
   if (lz4fRead == NULL)
-    return -LZ4F_ERROR_GENERIC;
-  LZ4F_freeDecompressionContext(lz4fRead->dctxPtr);
-  free(lz4fRead->srcBuf);
-  free(lz4fRead);
+    RETURN_ERROR(parameter_null);
+  LZ4F_freeReadFile(lz4fRead);
   return LZ4F_OK_NoError;
 }
 
+/* =====   write API   ===== */
+
+struct LZ4_writeFile_s {
+  LZ4F_cctx* cctxPtr;
+  FILE* fp;
+  LZ4_byte* dstBuf;
+  size_t maxWriteSize;
+  size_t dstBufMaxSize;
+  LZ4F_errorCode_t errCode;
+};
+
+static void LZ4F_freeWriteFile(LZ4_writeFile_t* state)
+{
+  if (state == NULL) return;
+  LZ4F_freeCompressionContext(state->cctxPtr);
+  free(state->dstBuf);
+  free(state);
+}
+
+static void LZ4F_freeAndNullWriteFile(LZ4_writeFile_t** statePtr)
+{
+  assert(statePtr != NULL);
+  LZ4F_freeWriteFile(*statePtr);
+  *statePtr = NULL;
+}
+
 LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4F_preferences_t* prefsPtr)
 {
   LZ4_byte buf[LZ4F_HEADER_SIZE_MAX];
   size_t ret;
 
   if (fp == NULL || lz4fWrite == NULL)
-    return -LZ4F_ERROR_GENERIC;
+    RETURN_ERROR(parameter_null);
 
-  *lz4fWrite = (LZ4_writeFile_t*)malloc(sizeof(LZ4_writeFile_t));
+  *lz4fWrite = (LZ4_writeFile_t*)calloc(1, sizeof(LZ4_writeFile_t));
   if (*lz4fWrite == NULL) {
-    return -LZ4F_ERROR_allocation_failed;
+    RETURN_ERROR(allocation_failed);
   }
   if (prefsPtr != NULL) {
     switch (prefsPtr->frameInfo.blockSizeID) {
@@ -206,8 +242,8 @@
         (*lz4fWrite)->maxWriteSize = 4 * 1024 * 1024;
         break;
       default:
-        free(lz4fWrite);
-        return -LZ4F_ERROR_maxBlockSize_invalid;
+        LZ4F_freeAndNullWriteFile(lz4fWrite);
+        RETURN_ERROR(maxBlockSize_invalid);
       }
     } else {
       (*lz4fWrite)->maxWriteSize = 64 * 1024;
@@ -216,30 +252,25 @@
   (*lz4fWrite)->dstBufMaxSize = LZ4F_compressBound((*lz4fWrite)->maxWriteSize, prefsPtr);
   (*lz4fWrite)->dstBuf = (LZ4_byte*)malloc((*lz4fWrite)->dstBufMaxSize);
   if ((*lz4fWrite)->dstBuf == NULL) {
-    free(*lz4fWrite);
-    return -LZ4F_ERROR_allocation_failed;
+    LZ4F_freeAndNullWriteFile(lz4fWrite);
+    RETURN_ERROR(allocation_failed);
   }
 
-  ret = LZ4F_createCompressionContext(&(*lz4fWrite)->cctxPtr, LZ4F_getVersion());
+  ret = LZ4F_createCompressionContext(&(*lz4fWrite)->cctxPtr, LZ4F_VERSION);
   if (LZ4F_isError(ret)) {
-      free((*lz4fWrite)->dstBuf);
-      free(*lz4fWrite);
+      LZ4F_freeAndNullWriteFile(lz4fWrite);
       return ret;
   }
 
   ret = LZ4F_compressBegin((*lz4fWrite)->cctxPtr, buf, LZ4F_HEADER_SIZE_MAX, prefsPtr);
   if (LZ4F_isError(ret)) {
-      LZ4F_freeCompressionContext((*lz4fWrite)->cctxPtr);
-      free((*lz4fWrite)->dstBuf);
-      free(*lz4fWrite);
+      LZ4F_freeAndNullWriteFile(lz4fWrite);
       return ret;
   }
 
   if (ret != fwrite(buf, 1, ret, fp)) {
-    LZ4F_freeCompressionContext((*lz4fWrite)->cctxPtr);
-    free((*lz4fWrite)->dstBuf);
-    free(*lz4fWrite);
-    return -LZ4F_ERROR_GENERIC;
+    LZ4F_freeAndNullWriteFile(lz4fWrite);
+    RETURN_ERROR(io_write);
   }
 
   (*lz4fWrite)->fp = fp;
@@ -247,15 +278,15 @@
   return LZ4F_OK_NoError;
 }
 
-size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, void* buf, size_t size)
+size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, const void* buf, size_t size)
 {
-  LZ4_byte* p = (LZ4_byte*)buf;
+  const LZ4_byte* p = (const LZ4_byte*)buf;
   size_t remain = size;
   size_t chunk;
   size_t ret;
 
   if (lz4fWrite == NULL || buf == NULL)
-    return -LZ4F_ERROR_GENERIC;
+    RETURN_ERROR(parameter_null);
   while (remain) {
     if (remain > lz4fWrite->maxWriteSize)
       chunk = lz4fWrite->maxWriteSize;
@@ -271,9 +302,9 @@
       return ret;
     }
 
-    if(ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
-      lz4fWrite->errCode = -LZ4F_ERROR_GENERIC;
-      return -LZ4F_ERROR_GENERIC;
+    if (ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
+      lz4fWrite->errCode = returnErrorCode(LZ4F_ERROR_io_write);
+      RETURN_ERROR(io_write);
     }
 
     p += chunk;
@@ -287,8 +318,9 @@
 {
   LZ4F_errorCode_t ret = LZ4F_OK_NoError;
 
-  if (lz4fWrite == NULL)
-    return -LZ4F_ERROR_GENERIC;
+  if (lz4fWrite == NULL) {
+    RETURN_ERROR(parameter_null);
+  }
 
   if (lz4fWrite->errCode == LZ4F_OK_NoError) {
     ret =  LZ4F_compressEnd(lz4fWrite->cctxPtr,
@@ -299,13 +331,11 @@
     }
 
     if (ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
-      ret = -LZ4F_ERROR_GENERIC;
+      ret = returnErrorCode(LZ4F_ERROR_io_write);
     }
   }
 
 out:
-  LZ4F_freeCompressionContext(lz4fWrite->cctxPtr);
-  free(lz4fWrite->dstBuf);
-  free(lz4fWrite);
+  LZ4F_freeWriteFile(lz4fWrite);
   return ret;
 }
diff --git a/lib/lz4file.h b/lib/lz4file.h
index 5527130..598ad70 100644
--- a/lib/lz4file.h
+++ b/lib/lz4file.h
@@ -38,7 +38,7 @@
 #ifndef LZ4FILE_H
 #define LZ4FILE_H
 
-#include <stdio.h>
+#include <stdio.h>  /* FILE* */
 #include "lz4frame_static.h"
 
 typedef struct LZ4_readFile_s LZ4_readFile_t;
@@ -78,7 +78,7 @@
  * `buf` write data buffer.
  * `size` write data buffer size.
  */
-LZ4FLIB_STATIC_API size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, void* buf, size_t size);
+LZ4FLIB_STATIC_API size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, const void* buf, size_t size);
 
 /*! LZ4F_writeClose() :
  * Close lz4file handle.
diff --git a/lib/lz4frame.c b/lib/lz4frame.c
index 174f9ae..f89c055 100644
--- a/lib/lz4frame.c
+++ b/lib/lz4frame.c
@@ -44,6 +44,7 @@
 /*-************************************
 *  Compiler Options
 **************************************/
+#include <limits.h>
 #ifdef _MSC_VER    /* Visual Studio */
 #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
 #endif
@@ -54,8 +55,8 @@
 **************************************/
 /*
  * LZ4F_HEAPMODE :
- * Select how default compression functions will allocate memory for their hash table,
- * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
+ * Control how LZ4F_compressFrame allocates the Compression State,
+ * either on stack (0:default, fastest), or in memory heap (1:requires malloc()).
  */
 #ifndef LZ4F_HEAPMODE
 #  define LZ4F_HEAPMODE 0
@@ -125,8 +126,9 @@
 
 static void LZ4F_free(void* p, LZ4F_CustomMem cmem)
 {
-    /* custom malloc defined : use it */
+    if (p == NULL) return;
     if (cmem.customFree != NULL) {
+        /* custom allocation defined : use it */
         cmem.customFree(cmem.opaqueState, p);
         return;
     }
@@ -153,7 +155,7 @@
 static int g_debuglog_enable = 1;
 #  define DEBUGLOG(l, ...) {                                  \
                 if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
-                    fprintf(stderr, __FILE__ ": ");           \
+                    fprintf(stderr, __FILE__ " (%i): ", __LINE__ );  \
                     fprintf(stderr, __VA_ARGS__);             \
                     fprintf(stderr, " \n");                   \
             }   }
@@ -186,9 +188,9 @@
 {
     const BYTE* const srcPtr = (const BYTE*)src;
     U32 value32 = srcPtr[0];
-    value32 += ((U32)srcPtr[1])<< 8;
-    value32 += ((U32)srcPtr[2])<<16;
-    value32 += ((U32)srcPtr[3])<<24;
+    value32 |= ((U32)srcPtr[1])<< 8;
+    value32 |= ((U32)srcPtr[2])<<16;
+    value32 |= ((U32)srcPtr[3])<<24;
     return value32;
 }
 
@@ -205,13 +207,13 @@
 {
     const BYTE* const srcPtr = (const BYTE*)src;
     U64 value64 = srcPtr[0];
-    value64 += ((U64)srcPtr[1]<<8);
-    value64 += ((U64)srcPtr[2]<<16);
-    value64 += ((U64)srcPtr[3]<<24);
-    value64 += ((U64)srcPtr[4]<<32);
-    value64 += ((U64)srcPtr[5]<<40);
-    value64 += ((U64)srcPtr[6]<<48);
-    value64 += ((U64)srcPtr[7]<<56);
+    value64 |= ((U64)srcPtr[1]<<8);
+    value64 |= ((U64)srcPtr[2]<<16);
+    value64 |= ((U64)srcPtr[3]<<24);
+    value64 |= ((U64)srcPtr[4]<<32);
+    value64 |= ((U64)srcPtr[5]<<40);
+    value64 |= ((U64)srcPtr[6]<<48);
+    value64 |= ((U64)srcPtr[7]<<56);
     return value64;
 }
 
@@ -257,14 +259,15 @@
 *  Structures and local types
 **************************************/
 
-typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_blockCompression_t;
+typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_BlockCompressMode_e;
+typedef enum { ctxNone, ctxFast, ctxHC } LZ4F_CtxType_e;
 
 typedef struct LZ4F_cctx_s
 {
     LZ4F_CustomMem cmem;
     LZ4F_preferences_t prefs;
     U32    version;
-    U32    cStage;
+    U32    cStage;     /* 0 : compression uninitialized ; 1 : initialized, can compress */
     const LZ4F_CDict* cdict;
     size_t maxBlockSize;
     size_t maxBufferSize;
@@ -275,8 +278,8 @@
     XXH32_state_t xxh;
     void*  lz4CtxPtr;
     U16    lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
-    U16    lz4CtxState; /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
-    LZ4F_blockCompression_t  blockCompression;
+    U16    lz4CtxType;  /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
+    LZ4F_BlockCompressMode_e  blockCompressMode;
 } LZ4F_cctx_t;
 
 
@@ -314,9 +317,14 @@
 
 #define RETURN_ERROR(e) return LZ4F_returnErrorCode(LZ4F_ERROR_ ## e)
 
-#define RETURN_ERROR_IF(c,e) if (c) RETURN_ERROR(e)
+#define RETURN_ERROR_IF(c,e) do {  \
+        if (c) {                   \
+            DEBUGLOG(3, "Error: " #c); \
+            RETURN_ERROR(e);       \
+        }                          \
+    } while (0)
 
-#define FORWARD_IF_ERROR(r)  if (LZ4F_isError(r)) return (r)
+#define FORWARD_IF_ERROR(r) do { if (LZ4F_isError(r)) return (r); } while (0)
 
 unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; }
 
@@ -429,6 +437,7 @@
     BYTE* dstPtr = dstStart;
     BYTE* const dstEnd = dstStart + dstCapacity;
 
+    DEBUGLOG(4, "LZ4F_compressFrame_usingCDict (srcSize=%u)", (unsigned)srcSize);
     if (preferencesPtr!=NULL)
         prefs = *preferencesPtr;
     else
@@ -494,7 +503,7 @@
         LZ4_initStream(&lz4ctx, sizeof(lz4ctx));
         cctxPtr->lz4CtxPtr = &lz4ctx;
         cctxPtr->lz4CtxAlloc = 1;
-        cctxPtr->lz4CtxState = 1;
+        cctxPtr->lz4CtxType = ctxFast;
     }
 #endif
     DEBUGLOG(4, "LZ4F_compressFrame");
@@ -539,18 +548,19 @@
         dictSize = 64 KB;
     }
     cdict->dictContent = LZ4F_malloc(dictSize, cmem);
+    /* note: using @cmem to allocate => can't use default create */
     cdict->fastCtx = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cmem);
-    if (cdict->fastCtx)
-        LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
     cdict->HCCtx = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cmem);
-    if (cdict->HCCtx)
-        LZ4_initStream(cdict->HCCtx, sizeof(LZ4_streamHC_t));
     if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) {
         LZ4F_freeCDict(cdict);
         return NULL;
     }
     memcpy(cdict->dictContent, dictStart, dictSize);
-    LZ4_loadDict (cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
+    LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
+    LZ4_loadDictSlow(cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
+    LZ4_initStreamHC(cdict->HCCtx, sizeof(LZ4_streamHC_t));
+    /* note: we don't know at this point which compression level is going to be used
+     * as a consequence, HCCtx is created for the more common HC mode */
     LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT);
     LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize);
     return cdict;
@@ -616,7 +626,6 @@
     return LZ4F_OK_NoError;
 }
 
-
 LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr)
 {
     if (cctxPtr != NULL) {  /* support free on NULL */
@@ -641,7 +650,7 @@
                             int level,
                             LZ4F_blockMode_t blockMode) {
     if (level < LZ4HC_CLEVEL_MIN) {
-        if (cdict != NULL || blockMode == LZ4F_blockLinked) {
+        if (cdict || blockMode == LZ4F_blockLinked) {
             /* In these cases, we will call LZ4_compress_fast_continue(),
              * which needs an already reset context. Otherwise, we'll call a
              * one-shot API. The non-continued APIs internally perform their own
@@ -649,11 +658,18 @@
              * tableType they need the context to be in. So in that case this
              * would be misguided / wasted work. */
             LZ4_resetStream_fast((LZ4_stream_t*)ctx);
+            if (cdict)
+                LZ4_attach_dictionary((LZ4_stream_t*)ctx, cdict->fastCtx);
         }
-        LZ4_attach_dictionary((LZ4_stream_t *)ctx, cdict ? cdict->fastCtx : NULL);
+        /* In these cases, we'll call a one-shot API.
+         * The non-continued APIs internally perform their own resets
+         * at the beginning of their calls, where they know
+         * which tableType they need the context to be in.
+         * Therefore, a reset here would be wasted work. */
     } else {
         LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level);
-        LZ4_attach_HC_dictionary((LZ4_streamHC_t *)ctx, cdict ? cdict->HCCtx : NULL);
+        if (cdict)
+            LZ4_attach_HC_dictionary((LZ4_streamHC_t*)ctx, cdict->HCCtx);
     }
 }
 
@@ -668,14 +684,12 @@
     }
 }
 
-/*! LZ4F_compressBegin_usingCDict() :
- *  init streaming compression AND writes frame header into @dstBuffer.
- * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- * @return : number of bytes written into @dstBuffer for the header
- *           or an error code (can be tested using LZ4F_isError())
+/* LZ4F_compressBegin_internal()
+ * Note: only accepts @cdict _or_ @dictBuffer as non NULL.
  */
-size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,
+size_t LZ4F_compressBegin_internal(LZ4F_cctx* cctx,
                           void* dstBuffer, size_t dstCapacity,
+                          const void* dictBuffer, size_t dictSize,
                           const LZ4F_CDict* cdict,
                           const LZ4F_preferences_t* preferencesPtr)
 {
@@ -685,70 +699,84 @@
 
     RETURN_ERROR_IF(dstCapacity < maxFHSize, dstMaxSize_tooSmall);
     if (preferencesPtr == NULL) preferencesPtr = &prefNull;
-    cctxPtr->prefs = *preferencesPtr;
+    cctx->prefs = *preferencesPtr;
 
     /* cctx Management */
-    {   U16 const ctxTypeID = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2;
+    {   U16 const ctxTypeID = (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2;
         int requiredSize = ctxTypeID_to_size(ctxTypeID);
-        int allocatedSize = ctxTypeID_to_size(cctxPtr->lz4CtxAlloc);
+        int allocatedSize = ctxTypeID_to_size(cctx->lz4CtxAlloc);
         if (allocatedSize < requiredSize) {
             /* not enough space allocated */
-            LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);
-            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
+            LZ4F_free(cctx->lz4CtxPtr, cctx->cmem);
+            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
                 /* must take ownership of memory allocation,
                  * in order to respect custom allocator contract */
-                cctxPtr->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_stream_t), cctxPtr->cmem);
-                if (cctxPtr->lz4CtxPtr)
-                    LZ4_initStream(cctxPtr->lz4CtxPtr, sizeof(LZ4_stream_t));
+                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_stream_t), cctx->cmem);
+                if (cctx->lz4CtxPtr)
+                    LZ4_initStream(cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
             } else {
-                cctxPtr->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_streamHC_t), cctxPtr->cmem);
-                if (cctxPtr->lz4CtxPtr)
-                    LZ4_initStreamHC(cctxPtr->lz4CtxPtr, sizeof(LZ4_streamHC_t));
+                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_streamHC_t), cctx->cmem);
+                if (cctx->lz4CtxPtr)
+                    LZ4_initStreamHC(cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
             }
-            RETURN_ERROR_IF(cctxPtr->lz4CtxPtr == NULL, allocation_failed);
-            cctxPtr->lz4CtxAlloc = ctxTypeID;
-            cctxPtr->lz4CtxState = ctxTypeID;
-        } else if (cctxPtr->lz4CtxState != ctxTypeID) {
+            RETURN_ERROR_IF(cctx->lz4CtxPtr == NULL, allocation_failed);
+            cctx->lz4CtxAlloc = ctxTypeID;
+            cctx->lz4CtxType = ctxTypeID;
+        } else if (cctx->lz4CtxType != ctxTypeID) {
             /* otherwise, a sufficient buffer is already allocated,
              * but we need to reset it to the correct context type */
-            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
-                LZ4_initStream((LZ4_stream_t*)cctxPtr->lz4CtxPtr, sizeof(LZ4_stream_t));
+            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
+                LZ4_initStream((LZ4_stream_t*)cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
             } else {
-                LZ4_initStreamHC((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, sizeof(LZ4_streamHC_t));
-                LZ4_setCompressionLevel((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
+                LZ4_initStreamHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
+                LZ4_setCompressionLevel((LZ4_streamHC_t*)cctx->lz4CtxPtr, cctx->prefs.compressionLevel);
             }
-            cctxPtr->lz4CtxState = ctxTypeID;
+            cctx->lz4CtxType = ctxTypeID;
     }   }
 
     /* Buffer Management */
-    if (cctxPtr->prefs.frameInfo.blockSizeID == 0)
-        cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
-    cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);
+    if (cctx->prefs.frameInfo.blockSizeID == 0)
+        cctx->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
+    cctx->maxBlockSize = LZ4F_getBlockSize(cctx->prefs.frameInfo.blockSizeID);
 
     {   size_t const requiredBuffSize = preferencesPtr->autoFlush ?
-                ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */
-                cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
+                ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */
+                cctx->maxBlockSize + ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
 
-        if (cctxPtr->maxBufferSize < requiredBuffSize) {
-            cctxPtr->maxBufferSize = 0;
-            LZ4F_free(cctxPtr->tmpBuff, cctxPtr->cmem);
-            cctxPtr->tmpBuff = (BYTE*)LZ4F_calloc(requiredBuffSize, cctxPtr->cmem);
-            RETURN_ERROR_IF(cctxPtr->tmpBuff == NULL, allocation_failed);
-            cctxPtr->maxBufferSize = requiredBuffSize;
+        if (cctx->maxBufferSize < requiredBuffSize) {
+            cctx->maxBufferSize = 0;
+            LZ4F_free(cctx->tmpBuff, cctx->cmem);
+            cctx->tmpBuff = (BYTE*)LZ4F_malloc(requiredBuffSize, cctx->cmem);
+            RETURN_ERROR_IF(cctx->tmpBuff == NULL, allocation_failed);
+            cctx->maxBufferSize = requiredBuffSize;
     }   }
-    cctxPtr->tmpIn = cctxPtr->tmpBuff;
-    cctxPtr->tmpInSize = 0;
-    (void)XXH32_reset(&(cctxPtr->xxh), 0);
+    cctx->tmpIn = cctx->tmpBuff;
+    cctx->tmpInSize = 0;
+    (void)XXH32_reset(&(cctx->xxh), 0);
 
     /* context init */
-    cctxPtr->cdict = cdict;
-    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) {
+    cctx->cdict = cdict;
+    if (cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) {
         /* frame init only for blockLinked : blockIndependent will be init at each block */
-        LZ4F_initStream(cctxPtr->lz4CtxPtr, cdict, cctxPtr->prefs.compressionLevel, LZ4F_blockLinked);
+        LZ4F_initStream(cctx->lz4CtxPtr, cdict, cctx->prefs.compressionLevel, LZ4F_blockLinked);
     }
     if (preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) {
-        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);
+        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctx->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);
     }
+    if (dictBuffer) {
+        assert(cdict == NULL);
+        RETURN_ERROR_IF(dictSize > INT_MAX, parameter_invalid);
+        if (cctx->lz4CtxType == ctxFast) {
+            /* lz4 fast*/
+            LZ4_loadDict((LZ4_stream_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
+        } else {
+            /* lz4hc */
+            assert(cctx->lz4CtxType == ctxHC);
+            LZ4_loadDictHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
+        }
+    }
+
+    /* Stage 2 : Write Frame Header */
 
     /* Magic Number */
     LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
@@ -757,22 +785,22 @@
 
         /* FLG Byte */
         *dstPtr++ = (BYTE)(((1 & _2BITS) << 6)    /* Version('01') */
-            + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5)
-            + ((cctxPtr->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
-            + ((unsigned)(cctxPtr->prefs.frameInfo.contentSize > 0) << 3)
-            + ((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
-            +  (cctxPtr->prefs.frameInfo.dictID > 0) );
+            + ((cctx->prefs.frameInfo.blockMode & _1BIT ) << 5)
+            + ((cctx->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
+            + ((unsigned)(cctx->prefs.frameInfo.contentSize > 0) << 3)
+            + ((cctx->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
+            +  (cctx->prefs.frameInfo.dictID > 0) );
         /* BD Byte */
-        *dstPtr++ = (BYTE)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);
+        *dstPtr++ = (BYTE)((cctx->prefs.frameInfo.blockSizeID & _3BITS) << 4);
         /* Optional Frame content size field */
-        if (cctxPtr->prefs.frameInfo.contentSize) {
-            LZ4F_writeLE64(dstPtr, cctxPtr->prefs.frameInfo.contentSize);
+        if (cctx->prefs.frameInfo.contentSize) {
+            LZ4F_writeLE64(dstPtr, cctx->prefs.frameInfo.contentSize);
             dstPtr += 8;
-            cctxPtr->totalInSize = 0;
+            cctx->totalInSize = 0;
         }
         /* Optional dictionary ID field */
-        if (cctxPtr->prefs.frameInfo.dictID) {
-            LZ4F_writeLE32(dstPtr, cctxPtr->prefs.frameInfo.dictID);
+        if (cctx->prefs.frameInfo.dictID) {
+            LZ4F_writeLE32(dstPtr, cctx->prefs.frameInfo.dictID);
             dstPtr += 4;
         }
         /* Header CRC Byte */
@@ -780,24 +808,54 @@
         dstPtr++;
     }
 
-    cctxPtr->cStage = 1;   /* header written, now request input data block */
+    cctx->cStage = 1;   /* header written, now request input data block */
     return (size_t)(dstPtr - dstStart);
 }
 
-
-/*! LZ4F_compressBegin() :
- *  init streaming compression AND writes frame header into @dstBuffer.
- * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- * @preferencesPtr can be NULL, in which case default parameters are selected.
- * @return : number of bytes written into dstBuffer for the header
- *        or an error code (can be tested using LZ4F_isError())
- */
-size_t LZ4F_compressBegin(LZ4F_cctx* cctxPtr,
+size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
                           void* dstBuffer, size_t dstCapacity,
                           const LZ4F_preferences_t* preferencesPtr)
 {
-    return LZ4F_compressBegin_usingCDict(cctxPtr, dstBuffer, dstCapacity,
-                                         NULL, preferencesPtr);
+    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
+                                        NULL, 0,
+                                        NULL, preferencesPtr);
+}
+
+/* LZ4F_compressBegin_usingDictOnce:
+ * Hidden implementation,
+ * employed for multi-threaded compression
+ * when frame defines linked blocks */
+size_t LZ4F_compressBegin_usingDictOnce(LZ4F_cctx* cctx,
+                          void* dstBuffer, size_t dstCapacity,
+                          const void* dict, size_t dictSize,
+                          const LZ4F_preferences_t* preferencesPtr)
+{
+    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
+                                        dict, dictSize,
+                                        NULL, preferencesPtr);
+}
+
+size_t LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
+                          void* dstBuffer, size_t dstCapacity,
+                          const void* dict, size_t dictSize,
+                          const LZ4F_preferences_t* preferencesPtr)
+{
+    /* note : incorrect implementation :
+     * this will only use the dictionary once,
+     * instead of once *per* block when frames defines independent blocks */
+    return LZ4F_compressBegin_usingDictOnce(cctx, dstBuffer, dstCapacity,
+                                        dict, dictSize,
+                                        preferencesPtr);
+}
+
+size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
+                          void* dstBuffer, size_t dstCapacity,
+                          const LZ4F_CDict* cdict,
+                          const LZ4F_preferences_t* preferencesPtr)
+{
+    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
+                                        NULL, 0,
+                                       cdict, preferencesPtr);
 }
 
 
@@ -891,9 +949,10 @@
     return 0;
 }
 
-static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_blockCompression_t  compressMode)
+static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_BlockCompressMode_e  compressMode)
 {
-    if (compressMode == LZ4B_UNCOMPRESSED) return LZ4F_doNotCompressBlock;
+    if (compressMode == LZ4B_UNCOMPRESSED)
+        return LZ4F_doNotCompressBlock;
     if (level < LZ4HC_CLEVEL_MIN) {
         if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock;
         return LZ4F_compressBlock_continue;
@@ -931,7 +990,7 @@
                      void* dstBuffer, size_t dstCapacity,
                      const void* srcBuffer, size_t srcSize,
                      const LZ4F_compressOptions_t* compressOptionsPtr,
-                     LZ4F_blockCompression_t blockCompression)
+                     LZ4F_BlockCompressMode_e blockCompression)
   {
     size_t const blockSize = cctxPtr->maxBlockSize;
     const BYTE* srcPtr = (const BYTE*)srcBuffer;
@@ -951,10 +1010,10 @@
         RETURN_ERROR(dstMaxSize_tooSmall);
 
     /* flush currently written block, to continue with new block compression */
-    if (cctxPtr->blockCompression != blockCompression) {
+    if (cctxPtr->blockCompressMode != blockCompression) {
         bytesWritten = LZ4F_flush(cctxPtr, dstBuffer, dstCapacity, compressOptionsPtr);
         dstPtr += bytesWritten;
-        cctxPtr->blockCompression = blockCompression;
+        cctxPtr->blockCompressMode = blockCompression;
     }
 
     if (compressOptionsPtr == NULL) compressOptionsPtr = &k_cOptionsNull;
@@ -1068,13 +1127,9 @@
                                    compressOptionsPtr, LZ4B_COMPRESSED);
 }
 
-/*! LZ4F_compressUpdate() :
- *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
- *  When successful, the function always entirely consumes @srcBuffer.
- *  src data is either buffered or compressed into @dstBuffer.
- *  If previously an uncompressed block was written, buffered data is flushed
- *  before appending compressed data is continued.
- *  This is only supported when LZ4F_blockIndependent is used
+/*! LZ4F_uncompressedUpdate() :
+ *  Same as LZ4F_compressUpdate(), but requests blocks to be sent uncompressed.
+ *  This symbol is only supported when LZ4F_blockIndependent is used
  * @dstCapacity MUST be >= LZ4F_compressBound(srcSize, preferencesPtr).
  * @compressOptionsPtr is optional : provide NULL to mean "default".
  * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
@@ -1084,8 +1139,8 @@
 size_t LZ4F_uncompressedUpdate(LZ4F_cctx* cctxPtr,
                                void* dstBuffer, size_t dstCapacity,
                          const void* srcBuffer, size_t srcSize,
-                         const LZ4F_compressOptions_t* compressOptionsPtr) {
-    RETURN_ERROR_IF(cctxPtr->prefs.frameInfo.blockMode != LZ4F_blockIndependent, blockMode_invalid);
+                         const LZ4F_compressOptions_t* compressOptionsPtr)
+{
     return LZ4F_compressUpdateImpl(cctxPtr,
                                    dstBuffer, dstCapacity,
                                    srcBuffer, srcSize,
@@ -1115,7 +1170,7 @@
     (void)compressOptionsPtr;   /* not useful (yet) */
 
     /* select compression function */
-    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompression);
+    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompressMode);
 
     /* compress tmp buffer */
     dstPtr += LZ4F_makeBlock(dstPtr,
@@ -1170,13 +1225,12 @@
     if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) {
         U32 const xxh = XXH32_digest(&(cctxPtr->xxh));
         RETURN_ERROR_IF(dstCapacity < 8, dstMaxSize_tooSmall);
-        DEBUGLOG(5,"Writing 32-bit content checksum");
+        DEBUGLOG(5,"Writing 32-bit content checksum (0x%0X)", xxh);
         LZ4F_writeLE32(dstPtr, xxh);
         dstPtr+=4;   /* content Checksum */
     }
 
     cctxPtr->cStage = 0;   /* state is now re-usable (with identical preferences) */
-    cctxPtr->maxBufferSize = 0;  /* reuse HC context */
 
     if (cctxPtr->prefs.frameInfo.contentSize) {
         if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)
@@ -1270,13 +1324,14 @@
 
 
 /*==---   Streaming Decompression operations   ---==*/
-
 void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx)
 {
+    DEBUGLOG(5, "LZ4F_resetDecompressionContext");
     dctx->dStage = dstage_getFrameHeader;
     dctx->dict = NULL;
     dctx->dictSize = 0;
     dctx->skipChecksum = 0;
+    dctx->frameRemainingSize = 0;
 }
 
 
@@ -1333,6 +1388,7 @@
         if (((FLG>>1)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */
         if (version != 1) RETURN_ERROR(headerVersion_wrong);       /* Version Number, only supported value */
     }
+    DEBUGLOG(6, "contentSizeFlag: %u", contentSizeFlag);
 
     /* Frame Header Size */
     frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
@@ -1369,8 +1425,9 @@
     dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag;
     dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID;
     dctx->maxBlockSize = LZ4F_getBlockSize((LZ4F_blockSizeID_t)blockSizeID);
-    if (contentSizeFlag)
+    if (contentSizeFlag) {
         dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6);
+    }
     if (dictIDFlag)
         dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5);
 
@@ -1570,7 +1627,7 @@
     size_t nextSrcSizeHint = 1;
 
 
-    DEBUGLOG(5, "LZ4F_decompress : %p,%u => %p,%u",
+    DEBUGLOG(5, "LZ4F_decompress: src[%p](%u) => dst[%p](%u)",
             srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr);
     if (dstBuffer == NULL) assert(*dstSizePtr == 0);
     MEM_INIT(&optionsNull, 0, sizeof(optionsNull));
@@ -1722,10 +1779,10 @@
                     /* history management (linked blocks only)*/
                     if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {
                         LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0);
-                }   }
-
-                srcPtr += sizeToCopy;
-                dstPtr += sizeToCopy;
+                    }
+                    srcPtr += sizeToCopy;
+                    dstPtr += sizeToCopy;
+                }
                 if (sizeToCopy == dctx->tmpInTarget) {   /* all done */
                     if (dctx->frameInfo.blockChecksumFlag) {
                         dctx->tmpInSize = 0;
@@ -1959,6 +2016,7 @@
             if (!dctx->skipChecksum) {
                 U32 const readCRC = LZ4F_readLE32(selectedIn);
                 U32 const resultCRC = XXH32_digest(&(dctx->xxh));
+                DEBUGLOG(4, "frame checksum: stored 0x%0X vs 0x%0X processed", readCRC, resultCRC);
 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
                 RETURN_ERROR_IF(readCRC != resultCRC, contentChecksum_invalid);
 #else
diff --git a/lib/lz4frame.h b/lib/lz4frame.h
index 1bdf6c4..b8ae322 100644
--- a/lib/lz4frame.h
+++ b/lib/lz4frame.h
@@ -173,16 +173,16 @@
  *  setting all parameters to default.
  *  It's then possible to update selectively some parameters */
 typedef struct {
-  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default */
-  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */
-  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */
+  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default (LZ4F_max64KB) */
+  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default (LZ4F_blockLinked) */
+  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: add a 32-bit checksum of frame's decompressed data; 0 == default (disabled) */
   LZ4F_frameType_t       frameType;           /* read-only field : LZ4F_frame or LZ4F_skippableFrame */
   unsigned long long     contentSize;         /* Size of uncompressed content ; 0 == unknown */
   unsigned               dictID;              /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */
-  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */
+  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0 == default (disabled) */
 } LZ4F_frameInfo_t;
 
-#define LZ4F_INIT_FRAMEINFO   { LZ4F_default, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum }    /* v1.8.3+ */
+#define LZ4F_INIT_FRAMEINFO   { LZ4F_max64KB, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum }    /* v1.8.3+ */
 
 /*! LZ4F_preferences_t :
  *  makes it possible to supply advanced compression instructions to streaming interface.
@@ -204,7 +204,26 @@
 *  Simple compression function
 ***********************************/
 
-LZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
+/*! LZ4F_compressFrame() :
+ *  Compress srcBuffer content into an LZ4-compressed frame.
+ *  It's a one shot operation, all input content is consumed, and all output is generated.
+ *
+ *  Note : it's a stateless operation (no LZ4F_cctx state needed).
+ *  In order to reduce load on the allocator, LZ4F_compressFrame(), by default,
+ *  uses the stack to allocate space for the compression state and some table.
+ *  If this usage of the stack is too much for your application,
+ *  consider compiling `lz4frame.c` with compile-time macro LZ4F_HEAPMODE set to 1 instead.
+ *  All state allocations will use the Heap.
+ *  It also means each invocation of LZ4F_compressFrame() will trigger several internal alloc/free invocations.
+ *
+ * @dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
+ * @preferencesPtr is optional : one can provide NULL, in which case all preferences are set to default.
+ * @return : number of bytes written into dstBuffer.
+ *           or an error code if it fails (can be tested using LZ4F_isError())
+ */
+LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
+                                const void* srcBuffer, size_t srcSize,
+                                const LZ4F_preferences_t* preferencesPtr);
 
 /*! LZ4F_compressFrameBound() :
  *  Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences.
@@ -214,16 +233,11 @@
  */
 LZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
 
-/*! LZ4F_compressFrame() :
- *  Compress an entire srcBuffer into a valid LZ4 frame.
- *  dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
- *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
- * @return : number of bytes written into dstBuffer.
- *           or an error code if it fails (can be tested using LZ4F_isError())
+
+/*! LZ4F_compressionLevel_max() :
+ * @return maximum allowed compression level (currently: 12)
  */
-LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
-                                const void* srcBuffer, size_t srcSize,
-                                const LZ4F_preferences_t* preferencesPtr);
+LZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
 
 
 /*-***********************************
@@ -278,7 +292,7 @@
 /*! LZ4F_compressBegin() :
  *  will write the frame header into dstBuffer.
  *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- * `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default.
+ * `prefsPtr` is optional : NULL can be provided to set all preferences to default.
  * @return : number of bytes written into dstBuffer for the header
  *           or an error code (which can be tested using LZ4F_isError())
  */
@@ -355,8 +369,9 @@
 typedef LZ4F_dctx* LZ4F_decompressionContext_t;   /* compatibility with previous API versions */
 
 typedef struct {
-  unsigned stableDst;     /* pledges that last 64KB decompressed data will remain available unmodified between invocations.
-                           * This optimization skips storage operations in tmp buffers. */
+  unsigned stableDst;     /* pledges that last 64KB decompressed data is present right before @dstBuffer pointer.
+                           * This optimization skips internal storage operations.
+                           * Once set, this pledge must remain valid up to the end of current frame. */
   unsigned skipChecksums; /* disable checksum calculation and verification, even when one is present in frame, to save CPU time.
                            * Setting this option to 1 once disables all checksums for the rest of the frame. */
   unsigned reserved1;     /* must be set to zero for forward compatibility */
@@ -463,6 +478,11 @@
  * `dstBuffer` can freely change between each consecutive function invocation.
  * `dstBuffer` content will be overwritten.
  *
+ *  Note: if `LZ4F_getFrameInfo()` is called before `LZ4F_decompress()`, srcBuffer must be updated to reflect
+ *  the number of bytes consumed after reading the frame header. Failure to update srcBuffer before calling
+ *  `LZ4F_decompress()` will cause decompression failure or, even worse, successful but incorrect decompression.
+ *  See the `LZ4F_getFrameInfo()` docs for details.
+ *
  * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.
  *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.
  *  Respecting the hint provides some small speed benefit, because it skips intermediate buffers.
@@ -493,6 +513,109 @@
 LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx);   /* always successful */
 
 
+/**********************************
+ *  Dictionary compression API
+ *********************************/
+
+/* A Dictionary is useful for the compression of small messages (KB range).
+ * It dramatically improves compression efficiency.
+ *
+ * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.
+ * Better results are generally achieved by using Zstandard's Dictionary Builder
+ * to generate a high-quality dictionary from a set of samples.
+ *
+ * The same dictionary will have to be used on the decompression side
+ * for decoding to be successful.
+ * To help identify the correct dictionary at decoding stage,
+ * the frame header allows optional embedding of a dictID field.
+ */
+
+/*! LZ4F_compressBegin_usingDict() : stable since v1.10
+ *  Inits dictionary compression streaming, and writes the frame header into dstBuffer.
+ * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
+ * @prefsPtr is optional : one may provide NULL as argument,
+ *  however, it's the only way to provide dictID in the frame header.
+ * @dictBuffer must outlive the compression session.
+ * @return : number of bytes written into dstBuffer for the header,
+ *           or an error code (which can be tested using LZ4F_isError())
+ *  NOTE: The LZ4Frame spec allows each independent block to be compressed with the dictionary,
+ *        but this entry supports a more limited scenario, where only the first block uses the dictionary.
+ *        This is still useful for small data, which only need one block anyway.
+ *        For larger inputs, one may be more interested in LZ4F_compressFrame_usingCDict() below.
+ */
+LZ4FLIB_API size_t
+LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
+                            void* dstBuffer, size_t dstCapacity,
+                      const void* dictBuffer, size_t dictSize,
+                      const LZ4F_preferences_t* prefsPtr);
+
+/*! LZ4F_decompress_usingDict() : stable since v1.10
+ *  Same as LZ4F_decompress(), using a predefined dictionary.
+ *  Dictionary is used "in place", without any preprocessing.
+**  It must remain accessible throughout the entire frame decoding. */
+LZ4FLIB_API size_t
+LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
+                          void* dstBuffer, size_t* dstSizePtr,
+                    const void* srcBuffer, size_t* srcSizePtr,
+                    const void* dict, size_t dictSize,
+                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
+
+/*****************************************
+ *  Bulk processing dictionary compression
+ *****************************************/
+
+/* Loading a dictionary has a cost, since it involves construction of tables.
+ * The Bulk processing dictionary API makes it possible to share this cost
+ * over an arbitrary number of compression jobs, even concurrently,
+ * markedly improving compression latency for these cases.
+ *
+ * Note that there is no corresponding bulk API for the decompression side,
+ * because dictionary does not carry any initialization cost for decompression.
+ * Use the regular LZ4F_decompress_usingDict() there.
+ */
+typedef struct LZ4F_CDict_s LZ4F_CDict;
+
+/*! LZ4_createCDict() : stable since v1.10
+ *  When compressing multiple messages / blocks using the same dictionary, it's recommended to initialize it just once.
+ *  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
+ *  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
+ * @dictBuffer can be released after LZ4_CDict creation, since its content is copied within CDict. */
+LZ4FLIB_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
+LZ4FLIB_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
+
+/*! LZ4_compressFrame_usingCDict() : stable since v1.10
+ *  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
+ * @cctx must point to a context created by LZ4F_createCompressionContext().
+ *  If @cdict==NULL, compress without a dictionary.
+ * @dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
+ *  If this condition is not respected, function will fail (@return an errorCode).
+ *  The LZ4F_preferences_t structure is optional : one may provide NULL as argument,
+ *  but it's not recommended, as it's the only way to provide @dictID in the frame header.
+ * @return : number of bytes written into dstBuffer.
+ *           or an error code if it fails (can be tested using LZ4F_isError())
+ *  Note: for larger inputs generating multiple independent blocks,
+ *        this entry point uses the dictionary for each block. */
+LZ4FLIB_API size_t
+LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
+                              void* dst, size_t dstCapacity,
+                        const void* src, size_t srcSize,
+                        const LZ4F_CDict* cdict,
+                        const LZ4F_preferences_t* preferencesPtr);
+
+/*! LZ4F_compressBegin_usingCDict() : stable since v1.10
+ *  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
+ * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
+ * @prefsPtr is optional : one may provide NULL as argument,
+ *  note however that it's the only way to insert a @dictID in the frame header.
+ * @cdict must outlive the compression session.
+ * @return : number of bytes written into dstBuffer for the header,
+ *           or an error code, which can be tested using LZ4F_isError(). */
+LZ4FLIB_API size_t
+LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
+                              void* dstBuffer, size_t dstCapacity,
+                        const LZ4F_CDict* cdict,
+                        const LZ4F_preferences_t* prefsPtr);
+
 
 #if defined (__cplusplus)
 }
@@ -503,11 +626,8 @@
 #if defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843)
 #define LZ4F_H_STATIC_09782039843
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-/* These declarations are not stable and may change in the future.
+/* Note :
+ * The below declarations are not stable and may change in the future.
  * They are therefore only safe to depend on
  * when the caller is statically linked against the library.
  * To access their declarations, define LZ4F_STATIC_LINKING_ONLY.
@@ -517,6 +637,11 @@
  * by defining LZ4F_PUBLISH_STATIC_FUNCTIONS.
  * Use at your own risk.
  */
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #ifdef LZ4F_PUBLISH_STATIC_FUNCTIONS
 # define LZ4FLIB_STATIC_API LZ4FLIB_API
 #else
@@ -530,7 +655,7 @@
         ITEM(ERROR_GENERIC) \
         ITEM(ERROR_maxBlockSize_invalid) \
         ITEM(ERROR_blockMode_invalid) \
-        ITEM(ERROR_contentChecksumFlag_invalid) \
+        ITEM(ERROR_parameter_invalid) \
         ITEM(ERROR_compressionLevel_invalid) \
         ITEM(ERROR_headerVersion_wrong) \
         ITEM(ERROR_blockChecksum_invalid) \
@@ -548,6 +673,8 @@
         ITEM(ERROR_frameDecoding_alreadyStarted) \
         ITEM(ERROR_compressionState_uninitialized) \
         ITEM(ERROR_parameter_null) \
+        ITEM(ERROR_io_write) \
+        ITEM(ERROR_io_read) \
         ITEM(ERROR_maxCode)
 
 #define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM,
@@ -558,22 +685,26 @@
 
 LZ4FLIB_STATIC_API LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult);
 
+/**********************************
+ *  Advanced compression operations
+ *********************************/
 
 /*! LZ4F_getBlockSize() :
- *  Return, in scalar format (size_t),
- *  the maximum block size associated with blockSizeID.
+ * @return, in scalar format (size_t),
+ *          the maximum block size associated with @blockSizeID,
+ *          or an error code (can be tested using LZ4F_isError()) if @blockSizeID is invalid.
 **/
 LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
 
 /*! LZ4F_uncompressedUpdate() :
- *  LZ4F_uncompressedUpdate() can be called repetitively to add as much data uncompressed data as necessary.
+ *  LZ4F_uncompressedUpdate() can be called repetitively to add data stored as uncompressed blocks.
  *  Important rule: dstCapacity MUST be large enough to store the entire source buffer as
  *  no compression is done for this operation
  *  If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode).
  *  After an error, the state is left in a UB state, and must be re-initialized or freed.
- *  If previously a compressed block was written, buffered data is flushed
+ *  If previously a compressed block was written, buffered data is flushed first,
  *  before appending uncompressed data is continued.
- *  This is only supported when LZ4F_blockIndependent is used
+ *  This operation is only supported when LZ4F_blockIndependent is used.
  * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
  * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
  *           or an error code if it fails (which can be tested using LZ4F_isError())
@@ -585,82 +716,10 @@
                   const LZ4F_compressOptions_t* cOptPtr);
 
 /**********************************
- *  Bulk processing dictionary API
+ *  Custom memory allocation
  *********************************/
 
-/* A Dictionary is useful for the compression of small messages (KB range).
- * It dramatically improves compression efficiency.
- *
- * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.
- * Best results are generally achieved by using Zstandard's Dictionary Builder
- * to generate a high-quality dictionary from a set of samples.
- *
- * Loading a dictionary has a cost, since it involves construction of tables.
- * The Bulk processing dictionary API makes it possible to share this cost
- * over an arbitrary number of compression jobs, even concurrently,
- * markedly improving compression latency for these cases.
- *
- * The same dictionary will have to be used on the decompression side
- * for decoding to be successful.
- * To help identify the correct dictionary at decoding stage,
- * the frame header allows optional embedding of a dictID field.
- */
-typedef struct LZ4F_CDict_s LZ4F_CDict;
-
-/*! LZ4_createCDict() :
- *  When compressing multiple messages / blocks using the same dictionary, it's recommended to load it just once.
- *  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
- *  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
- * `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict */
-LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
-LZ4FLIB_STATIC_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
-
-
-/*! LZ4_compressFrame_usingCDict() :
- *  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
- *  cctx must point to a context created by LZ4F_createCompressionContext().
- *  If cdict==NULL, compress without a dictionary.
- *  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
- *  If this condition is not respected, function will fail (@return an errorCode).
- *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,
- *  but it's not recommended, as it's the only way to provide dictID in the frame header.
- * @return : number of bytes written into dstBuffer.
- *           or an error code if it fails (can be tested using LZ4F_isError()) */
-LZ4FLIB_STATIC_API size_t
-LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
-                              void* dst, size_t dstCapacity,
-                        const void* src, size_t srcSize,
-                        const LZ4F_CDict* cdict,
-                        const LZ4F_preferences_t* preferencesPtr);
-
-
-/*! LZ4F_compressBegin_usingCDict() :
- *  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
- *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
- * `prefsPtr` is optional : you may provide NULL as argument,
- *  however, it's the only way to provide dictID in the frame header.
- * @return : number of bytes written into dstBuffer for the header,
- *           or an error code (which can be tested using LZ4F_isError()) */
-LZ4FLIB_STATIC_API size_t
-LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
-                              void* dstBuffer, size_t dstCapacity,
-                        const LZ4F_CDict* cdict,
-                        const LZ4F_preferences_t* prefsPtr);
-
-
-/*! LZ4F_decompress_usingDict() :
- *  Same as LZ4F_decompress(), using a predefined dictionary.
- *  Dictionary is used "in place", without any preprocessing.
-**  It must remain accessible throughout the entire frame decoding. */
-LZ4FLIB_STATIC_API size_t
-LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
-                          void* dstBuffer, size_t* dstSizePtr,
-                    const void* srcBuffer, size_t* srcSizePtr,
-                    const void* dict, size_t dictSize,
-                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
-
-
-/*! Custom memory allocation :
+/*! Custom memory allocation : v1.9.4+
  *  These prototypes make it possible to pass custom allocation/free functions.
  *  LZ4F_customMem is provided at state creation time, using LZ4F_create*_advanced() listed below.
  *  All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.
diff --git a/lib/lz4hc.c b/lib/lz4hc.c
index b21ad6b..4d8c36a 100644
--- a/lib/lz4hc.c
+++ b/lib/lz4hc.c
@@ -39,9 +39,10 @@
 ***************************************/
 
 /*! HEAPMODE :
- *  Select how default compression function will allocate workplace memory,
- *  in stack (0:fastest), or in heap (1:requires malloc()).
- *  Since workplace is rather large, heap mode is recommended.
+ *  Select how stateless HC compression functions like `LZ4_compress_HC()`
+ *  allocate memory for their workspace:
+ *  in stack (0:fastest), or in heap (1:default, requires malloc()).
+ *  Since workspace is rather large, heap mode is recommended.
 **/
 #ifndef LZ4HC_HEAPMODE
 #  define LZ4HC_HEAPMODE 1
@@ -51,19 +52,19 @@
 /*===    Dependency    ===*/
 #define LZ4_HC_STATIC_LINKING_ONLY
 #include "lz4hc.h"
+#include <limits.h>
 
 
-/*===   Common definitions   ===*/
-#if defined(__GNUC__)
-#  pragma GCC diagnostic ignored "-Wunused-function"
-#endif
-#if defined (__clang__)
-#  pragma clang diagnostic ignored "-Wunused-function"
-#endif
-
-#define LZ4_COMMONDEFS_ONLY
+/*===   Shared lz4.c code   ===*/
 #ifndef LZ4_SRC_INCLUDED
-#include "lz4.c"   /* LZ4_count, constants, mem */
+# if defined(__GNUC__)
+#  pragma GCC diagnostic ignored "-Wunused-function"
+# endif
+# if defined (__clang__)
+#  pragma clang diagnostic ignored "-Wunused-function"
+# endif
+# define LZ4_COMMONDEFS_ONLY
+# include "lz4.c"   /* LZ4_count, constants, mem */
 #endif
 
 
@@ -79,17 +80,158 @@
 /*===   Macros   ===*/
 #define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
 #define MAX(a,b)   ( (a) > (b) ? (a) : (b) )
-#define HASH_FUNCTION(i)         (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
-#define DELTANEXTMAXD(p)         chainTable[(p) & LZ4HC_MAXD_MASK]    /* flexible, LZ4HC_MAXD dependent */
+
+
+/*===   Levels definition   ===*/
+typedef enum { lz4mid, lz4hc, lz4opt } lz4hc_strat_e;
+typedef struct {
+    lz4hc_strat_e strat;
+    int nbSearches;
+    U32 targetLength;
+} cParams_t;
+static const cParams_t k_clTable[LZ4HC_CLEVEL_MAX+1] = {
+    { lz4mid,    2, 16 },  /* 0, unused */
+    { lz4mid,    2, 16 },  /* 1, unused */
+    { lz4mid,    2, 16 },  /* 2 */
+    { lz4hc,     4, 16 },  /* 3 */
+    { lz4hc,     8, 16 },  /* 4 */
+    { lz4hc,    16, 16 },  /* 5 */
+    { lz4hc,    32, 16 },  /* 6 */
+    { lz4hc,    64, 16 },  /* 7 */
+    { lz4hc,   128, 16 },  /* 8 */
+    { lz4hc,   256, 16 },  /* 9 */
+    { lz4opt,   96, 64 },  /*10==LZ4HC_CLEVEL_OPT_MIN*/
+    { lz4opt,  512,128 },  /*11 */
+    { lz4opt,16384,LZ4_OPT_NUM },  /* 12==LZ4HC_CLEVEL_MAX */
+};
+
+static cParams_t LZ4HC_getCLevelParams(int cLevel)
+{
+    /* note : clevel convention is a bit different from lz4frame,
+     * possibly something worth revisiting for consistency */
+    if (cLevel < 1)
+        cLevel = LZ4HC_CLEVEL_DEFAULT;
+    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
+    return k_clTable[cLevel];
+}
+
+
+/*===   Hashing   ===*/
+#define LZ4HC_HASHSIZE 4
+#define HASH_FUNCTION(i)      (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
+static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
+
+#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
+/* lie to the compiler about data alignment; use with caution */
+static U64 LZ4_read64(const void* memPtr) { return *(const U64*) memPtr; }
+
+#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
+/* __pack instructions are safer, but compiler specific */
+LZ4_PACK(typedef struct { U64 u64; }) LZ4_unalign64;
+static U64 LZ4_read64(const void* ptr) { return ((const LZ4_unalign64*)ptr)->u64; }
+
+#else  /* safe and portable access using memcpy() */
+static U64 LZ4_read64(const void* memPtr)
+{
+    U64 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+#endif /* LZ4_FORCE_MEMORY_ACCESS */
+
+#define LZ4MID_HASHSIZE 8
+#define LZ4MID_HASHLOG (LZ4HC_HASH_LOG-1)
+#define LZ4MID_HASHTABLESIZE (1 << LZ4MID_HASHLOG)
+
+static U32 LZ4MID_hash4(U32 v) { return (v * 2654435761U) >> (32-LZ4MID_HASHLOG); }
+static U32 LZ4MID_hash4Ptr(const void* ptr) { return LZ4MID_hash4(LZ4_read32(ptr)); }
+/* note: hash7 hashes the lower 56-bits.
+ * It presumes input was read using little endian.*/
+static U32 LZ4MID_hash7(U64 v) { return (U32)(((v  << (64-56)) * 58295818150454627ULL) >> (64-LZ4MID_HASHLOG)) ; }
+static U64 LZ4_readLE64(const void* memPtr);
+static U32 LZ4MID_hash8Ptr(const void* ptr) { return LZ4MID_hash7(LZ4_readLE64(ptr)); }
+
+static U64 LZ4_readLE64(const void* memPtr)
+{
+    if (LZ4_isLittleEndian()) {
+        return LZ4_read64(memPtr);
+    } else {
+        const BYTE* p = (const BYTE*)memPtr;
+        /* note: relies on the compiler to simplify this expression */
+        return (U64)p[0] | ((U64)p[1]<<8) | ((U64)p[2]<<16) | ((U64)p[3]<<24)
+            | ((U64)p[4]<<32) | ((U64)p[5]<<40) | ((U64)p[6]<<48) | ((U64)p[7]<<56);
+    }
+}
+
+
+/*===   Count match length   ===*/
+LZ4_FORCE_INLINE
+unsigned LZ4HC_NbCommonBytes32(U32 val)
+{
+    assert(val != 0);
+    if (LZ4_isLittleEndian()) {
+#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
+        unsigned long r;
+        _BitScanReverse(&r, val);
+        return (unsigned)((31 - r) >> 3);
+#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
+                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
+                                        !defined(LZ4_FORCE_SW_BITCOUNT)
+        return (unsigned)__builtin_clz(val) >> 3;
+#     else
+        val >>= 8;
+        val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |
+              (val + 0x00FF0000)) >> 24;
+        return (unsigned)val ^ 3;
+#     endif
+    } else {
+#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
+        unsigned long r;
+        _BitScanForward(&r, val);
+        return (unsigned)(r >> 3);
+#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
+                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
+                                        !defined(LZ4_FORCE_SW_BITCOUNT)
+        return (unsigned)__builtin_ctz(val) >> 3;
+#     else
+        const U32 m = 0x01010101;
+        return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
+#     endif
+    }
+}
+
+/** LZ4HC_countBack() :
+ * @return : negative value, nb of common bytes before ip/match */
+LZ4_FORCE_INLINE
+int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
+                    const BYTE* const iMin, const BYTE* const mMin)
+{
+    int back = 0;
+    int const min = (int)MAX(iMin - ip, mMin - match);
+    assert(min <= 0);
+    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
+    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
+
+    while ((back - min) > 3) {
+        U32 const v = LZ4_read32(ip + back - 4) ^ LZ4_read32(match + back - 4);
+        if (v) {
+            return (back - (int)LZ4HC_NbCommonBytes32(v));
+        } else back -= 4; /* 4-byte step */
+    }
+    /* check remainder if any */
+    while ( (back > min)
+         && (ip[back-1] == match[back-1]) )
+            back--;
+    return back;
+}
+
+/*===   Chain table updates   ===*/
 #define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */
 /* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
 #define UPDATABLE(ip, op, anchor) &ip, &op, &anchor
 
-static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
-
 
 /**************************************
-*  HC Compression
+*  Init
 **************************************/
 static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)
 {
@@ -101,6 +243,7 @@
 {
     size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart);
     size_t newStartingOffset = bufferSize + hc4->dictLimit;
+    DEBUGLOG(5, "LZ4HC_init_internal");
     assert(newStartingOffset >= bufferSize);  /* check overflow */
     if (newStartingOffset > 1 GB) {
         LZ4HC_clearTables(hc4);
@@ -116,6 +259,524 @@
 }
 
 
+/**************************************
+*  Encode
+**************************************/
+/* LZ4HC_encodeSequence() :
+ * @return : 0 if ok,
+ *           1 if buffer issue detected */
+LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
+    const BYTE** _ip,
+    BYTE** _op,
+    const BYTE** _anchor,
+    int matchLength,
+    int offset,
+    limitedOutput_directive limit,
+    BYTE* oend)
+{
+#define ip      (*_ip)
+#define op      (*_op)
+#define anchor  (*_anchor)
+
+    size_t length;
+    BYTE* const token = op++;
+
+#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
+    static const BYTE* start = NULL;
+    static U32 totalCost = 0;
+    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start);
+    U32 const ll = (U32)(ip - anchor);
+    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
+    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
+    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
+    if (start==NULL) start = anchor;  /* only works for single segment */
+    /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
+    DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5i, cost:%4u + %5u",
+                pos,
+                (U32)(ip - anchor), matchLength, offset,
+                cost, totalCost);
+    totalCost += cost;
+#endif
+
+    /* Encode Literal length */
+    length = (size_t)(ip - anchor);
+    LZ4_STATIC_ASSERT(notLimited == 0);
+    /* Check output limit */
+    if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) {
+        DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
+                (int)length, (int)(oend - op));
+        return 1;
+    }
+    if (length >= RUN_MASK) {
+        size_t len = length - RUN_MASK;
+        *token = (RUN_MASK << ML_BITS);
+        for(; len >= 255 ; len -= 255) *op++ = 255;
+        *op++ = (BYTE)len;
+    } else {
+        *token = (BYTE)(length << ML_BITS);
+    }
+
+    /* Copy Literals */
+    LZ4_wildCopy8(op, anchor, op + length);
+    op += length;
+
+    /* Encode Offset */
+    assert(offset <= LZ4_DISTANCE_MAX );
+    assert(offset > 0);
+    LZ4_writeLE16(op, (U16)(offset)); op += 2;
+
+    /* Encode MatchLength */
+    assert(matchLength >= MINMATCH);
+    length = (size_t)matchLength - MINMATCH;
+    if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) {
+        DEBUGLOG(6, "Not enough room to write match length");
+        return 1;   /* Check output limit */
+    }
+    if (length >= ML_MASK) {
+        *token += ML_MASK;
+        length -= ML_MASK;
+        for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; }
+        if (length >= 255) { length -= 255; *op++ = 255; }
+        *op++ = (BYTE)length;
+    } else {
+        *token += (BYTE)(length);
+    }
+
+    /* Prepare next loop */
+    ip += matchLength;
+    anchor = ip;
+
+    return 0;
+
+#undef ip
+#undef op
+#undef anchor
+}
+
+
+typedef struct {
+    int off;
+    int len;
+    int back;  /* negative value */
+} LZ4HC_match_t;
+
+LZ4HC_match_t LZ4HC_searchExtDict(const BYTE* ip, U32 ipIndex,
+        const BYTE* const iLowLimit, const BYTE* const iHighLimit,
+        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex,
+        int currentBestML, int nbAttempts)
+{
+    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
+    U32 lDictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
+    U32 matchIndex = lDictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
+    int offset = 0, sBack = 0;
+    assert(lDictEndIndex <= 1 GB);
+    if (lDictMatchIndex>0)
+        DEBUGLOG(7, "lDictEndIndex = %zu, lDictMatchIndex = %u", lDictEndIndex, lDictMatchIndex);
+    while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
+        const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + lDictMatchIndex;
+
+        if (LZ4_read32(matchPtr) == LZ4_read32(ip)) {
+            int mlt;
+            int back = 0;
+            const BYTE* vLimit = ip + (lDictEndIndex - lDictMatchIndex);
+            if (vLimit > iHighLimit) vLimit = iHighLimit;
+            mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
+            back = (ip > iLowLimit) ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->prefixStart) : 0;
+            mlt -= back;
+            if (mlt > currentBestML) {
+                currentBestML = mlt;
+                offset = (int)(ipIndex - matchIndex);
+                sBack = back;
+                DEBUGLOG(7, "found match of length %i within extDictCtx", currentBestML);
+        }   }
+
+        {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, lDictMatchIndex);
+            lDictMatchIndex -= nextOffset;
+            matchIndex -= nextOffset;
+    }   }
+
+    {   LZ4HC_match_t md;
+        md.len = currentBestML;
+        md.off = offset;
+        md.back = sBack;
+        return md;
+    }
+}
+
+typedef LZ4HC_match_t (*LZ4MID_searchIntoDict_f)(const BYTE* ip, U32 ipIndex,
+        const BYTE* const iHighLimit,
+        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex);
+
+static LZ4HC_match_t LZ4MID_searchHCDict(const BYTE* ip, U32 ipIndex,
+        const BYTE* const iHighLimit,
+        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
+{
+    return LZ4HC_searchExtDict(ip,ipIndex,
+                            ip, iHighLimit,
+                            dictCtx, gDictEndIndex,
+                            MINMATCH-1, 2);
+}
+
+static LZ4HC_match_t LZ4MID_searchExtDict(const BYTE* ip, U32 ipIndex,
+        const BYTE* const iHighLimit,
+        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
+{
+    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
+    const U32* const hash4Table = dictCtx->hashTable;
+    const U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
+    DEBUGLOG(7, "LZ4MID_searchExtDict (ipIdx=%u)", ipIndex);
+
+    /* search long match first */
+    {   U32 l8DictMatchIndex = hash8Table[LZ4MID_hash8Ptr(ip)];
+        U32 m8Index = l8DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
+        assert(lDictEndIndex <= 1 GB);
+        if (ipIndex - m8Index <= LZ4_DISTANCE_MAX) {
+            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l8DictMatchIndex;
+            const size_t safeLen = MIN(lDictEndIndex - l8DictMatchIndex, (size_t)(iHighLimit - ip));
+            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
+            if (mlt >= MINMATCH) {
+                LZ4HC_match_t md;
+                DEBUGLOG(7, "Found long ExtDict match of len=%u", mlt);
+                md.len = mlt;
+                md.off = (int)(ipIndex - m8Index);
+                md.back = 0;
+                return md;
+            }
+        }
+    }
+
+    /* search for short match second */
+    {   U32 l4DictMatchIndex = hash4Table[LZ4MID_hash4Ptr(ip)];
+        U32 m4Index = l4DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
+        if (ipIndex - m4Index <= LZ4_DISTANCE_MAX) {
+            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l4DictMatchIndex;
+            const size_t safeLen = MIN(lDictEndIndex - l4DictMatchIndex, (size_t)(iHighLimit - ip));
+            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
+            if (mlt >= MINMATCH) {
+                LZ4HC_match_t md;
+                DEBUGLOG(7, "Found short ExtDict match of len=%u", mlt);
+                md.len = mlt;
+                md.off = (int)(ipIndex - m4Index);
+                md.back = 0;
+                return md;
+            }
+        }
+    }
+
+    /* nothing found */
+    {   LZ4HC_match_t const md = {0, 0, 0 };
+        return md;
+    }
+}
+
+/**************************************
+*  Mid Compression (level 2)
+**************************************/
+
+LZ4_FORCE_INLINE void
+LZ4MID_addPosition(U32* hTable, U32 hValue, U32 index)
+{
+    hTable[hValue] = index;
+}
+
+#define ADDPOS8(_p, _idx) LZ4MID_addPosition(hash8Table, LZ4MID_hash8Ptr(_p), _idx)
+#define ADDPOS4(_p, _idx) LZ4MID_addPosition(hash4Table, LZ4MID_hash4Ptr(_p), _idx)
+
+/* Fill hash tables with references into dictionary.
+ * The resulting table is only exploitable by LZ4MID (level 2) */
+static void
+LZ4MID_fillHTable (LZ4HC_CCtx_internal* cctx, const void* dict, size_t size)
+{
+    U32* const hash4Table = cctx->hashTable;
+    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
+    const BYTE* const prefixPtr = (const BYTE*)dict;
+    U32 const prefixIdx = cctx->dictLimit;
+    U32 const target = prefixIdx + (U32)size - LZ4MID_HASHSIZE;
+    U32 idx = cctx->nextToUpdate;
+    assert(dict == cctx->prefixStart);
+    DEBUGLOG(4, "LZ4MID_fillHTable (size:%zu)", size);
+    if (size <= LZ4MID_HASHSIZE)
+        return;
+
+    for (; idx < target; idx += 3) {
+        ADDPOS4(prefixPtr+idx-prefixIdx, idx);
+        ADDPOS8(prefixPtr+idx+1-prefixIdx, idx+1);
+    }
+
+    idx = (size > 32 KB + LZ4MID_HASHSIZE) ? target - 32 KB : cctx->nextToUpdate;
+    for (; idx < target; idx += 1) {
+        ADDPOS8(prefixPtr+idx-prefixIdx, idx);
+    }
+
+    cctx->nextToUpdate = target;
+}
+
+static LZ4MID_searchIntoDict_f select_searchDict_function(const LZ4HC_CCtx_internal* dictCtx)
+{
+    if (dictCtx == NULL) return NULL;
+    if (LZ4HC_getCLevelParams(dictCtx->compressionLevel).strat == lz4mid)
+        return LZ4MID_searchExtDict;
+    return LZ4MID_searchHCDict;
+}
+
+static int LZ4MID_compress (
+    LZ4HC_CCtx_internal* const ctx,
+    const char* const src,
+    char* const dst,
+    int* srcSizePtr,
+    int const maxOutputSize,
+    const limitedOutput_directive limit,
+    const dictCtx_directive dict
+    )
+{
+    U32* const hash4Table = ctx->hashTable;
+    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
+    const BYTE* ip = (const BYTE*)src;
+    const BYTE* anchor = ip;
+    const BYTE* const iend = ip + *srcSizePtr;
+    const BYTE* const mflimit = iend - MFLIMIT;
+    const BYTE* const matchlimit = (iend - LASTLITERALS);
+    const BYTE* const ilimit = (iend - LZ4MID_HASHSIZE);
+    BYTE* op = (BYTE*)dst;
+    BYTE* oend = op + maxOutputSize;
+
+    const BYTE* const prefixPtr = ctx->prefixStart;
+    const U32 prefixIdx = ctx->dictLimit;
+    const U32 ilimitIdx = (U32)(ilimit - prefixPtr) + prefixIdx;
+    const BYTE* const dictStart = ctx->dictStart;
+    const U32 dictIdx = ctx->lowLimit;
+    const U32 gDictEndIndex = ctx->lowLimit;
+    const LZ4MID_searchIntoDict_f searchIntoDict = (dict == usingDictCtxHc) ? select_searchDict_function(ctx->dictCtx) : NULL;
+    unsigned matchLength;
+    unsigned matchDistance;
+
+    /* input sanitization */
+    DEBUGLOG(5, "LZ4MID_compress (%i bytes)", *srcSizePtr);
+    if (dict == usingDictCtxHc) DEBUGLOG(5, "usingDictCtxHc");
+    assert(*srcSizePtr >= 0);
+    if (*srcSizePtr) assert(src != NULL);
+    if (maxOutputSize) assert(dst != NULL);
+    if (*srcSizePtr < 0) return 0;  /* invalid */
+    if (maxOutputSize < 0) return 0; /* invalid */
+    if (*srcSizePtr > LZ4_MAX_INPUT_SIZE) {
+        /* forbidden: no input is allowed to be that large */
+        return 0;
+    }
+    if (limit == fillOutput) oend -= LASTLITERALS;  /* Hack for support LZ4 format restriction */
+    if (*srcSizePtr < LZ4_minLength)
+        goto _lz4mid_last_literals;  /* Input too small, no compression (all literals) */
+
+    /* main loop */
+    while (ip <= mflimit) {
+        const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
+        /* search long match */
+        {   U32 const h8 = LZ4MID_hash8Ptr(ip);
+            U32 const pos8 = hash8Table[h8];
+            assert(h8 < LZ4MID_HASHTABLESIZE);
+            assert(pos8 < ipIndex);
+            LZ4MID_addPosition(hash8Table, h8, ipIndex);
+            if (ipIndex - pos8 <= LZ4_DISTANCE_MAX) {
+                /* match candidate found */
+                if (pos8 >= prefixIdx) {
+                    const BYTE* const matchPtr = prefixPtr + pos8 - prefixIdx;
+                    assert(matchPtr < ip);
+                    matchLength = LZ4_count(ip, matchPtr, matchlimit);
+                    if (matchLength >= MINMATCH) {
+                        DEBUGLOG(7, "found long match at pos %u (len=%u)", pos8, matchLength);
+                        matchDistance = ipIndex - pos8;
+                        goto _lz4mid_encode_sequence;
+                    }
+                } else {
+                    if (pos8 >= dictIdx) {
+                        /* extDict match candidate */
+                        const BYTE* const matchPtr = dictStart + (pos8 - dictIdx);
+                        const size_t safeLen = MIN(prefixIdx - pos8, (size_t)(matchlimit - ip));
+                        matchLength = LZ4_count(ip, matchPtr, ip + safeLen);
+                        if (matchLength >= MINMATCH) {
+                            DEBUGLOG(7, "found long match at ExtDict pos %u (len=%u)", pos8, matchLength);
+                            matchDistance = ipIndex - pos8;
+                            goto _lz4mid_encode_sequence;
+                        }
+                    }
+                }
+        }   }
+        /* search short match */
+        {   U32 const h4 = LZ4MID_hash4Ptr(ip);
+            U32 const pos4 = hash4Table[h4];
+            assert(h4 < LZ4MID_HASHTABLESIZE);
+            assert(pos4 < ipIndex);
+            LZ4MID_addPosition(hash4Table, h4, ipIndex);
+            if (ipIndex - pos4 <= LZ4_DISTANCE_MAX) {
+                /* match candidate found */
+                if (pos4 >= prefixIdx) {
+                /* only search within prefix */
+                    const BYTE* const matchPtr = prefixPtr + (pos4 - prefixIdx);
+                    assert(matchPtr < ip);
+                    assert(matchPtr >= prefixPtr);
+                    matchLength = LZ4_count(ip, matchPtr, matchlimit);
+                    if (matchLength >= MINMATCH) {
+                        /* short match found, let's just check ip+1 for longer */
+                        U32 const h8 = LZ4MID_hash8Ptr(ip+1);
+                        U32 const pos8 = hash8Table[h8];
+                        U32 const m2Distance = ipIndex + 1 - pos8;
+                        matchDistance = ipIndex - pos4;
+                        if ( m2Distance <= LZ4_DISTANCE_MAX
+                        && pos8 >= prefixIdx /* only search within prefix */
+                        && likely(ip < mflimit)
+                        ) {
+                            const BYTE* const m2Ptr = prefixPtr + (pos8 - prefixIdx);
+                            unsigned ml2 = LZ4_count(ip+1, m2Ptr, matchlimit);
+                            if (ml2 > matchLength) {
+                                LZ4MID_addPosition(hash8Table, h8, ipIndex+1);
+                                ip++;
+                                matchLength = ml2;
+                                matchDistance = m2Distance;
+                        }   }
+                        goto _lz4mid_encode_sequence;
+                    }
+                } else {
+                    if (pos4 >= dictIdx) {
+                        /* extDict match candidate */
+                        const BYTE* const matchPtr = dictStart + (pos4 - dictIdx);
+                        const size_t safeLen = MIN(prefixIdx - pos4, (size_t)(matchlimit - ip));
+                        matchLength = LZ4_count(ip, matchPtr, ip + safeLen);
+                        if (matchLength >= MINMATCH) {
+                            DEBUGLOG(7, "found match at ExtDict pos %u (len=%u)", pos4, matchLength);
+                            matchDistance = ipIndex - pos4;
+                            goto _lz4mid_encode_sequence;
+                        }
+                    }
+                }
+        }   }
+        /* no match found in prefix */
+        if ( (dict == usingDictCtxHc)
+          && (ipIndex - gDictEndIndex < LZ4_DISTANCE_MAX - 8) ) {
+            /* search a match into external dictionary */
+            LZ4HC_match_t dMatch = searchIntoDict(ip, ipIndex,
+                    matchlimit,
+                    ctx->dictCtx, gDictEndIndex);
+            if (dMatch.len >= MINMATCH) {
+                DEBUGLOG(7, "found Dictionary match (offset=%i)", dMatch.off);
+                assert(dMatch.back == 0);
+                matchLength = (unsigned)dMatch.len;
+                matchDistance = (unsigned)dMatch.off;
+                goto _lz4mid_encode_sequence;
+            }
+        }
+        /* no match found */
+        ip += 1 + ((ip-anchor) >> 9);  /* skip faster over incompressible data */
+        continue;
+
+_lz4mid_encode_sequence:
+        /* catch back */
+        while (((ip > anchor) & ((U32)(ip-prefixPtr) > matchDistance)) && (unlikely(ip[-1] == ip[-(int)matchDistance-1]))) {
+            ip--;  matchLength++;
+        };
+
+        /* fill table with beginning of match */
+        ADDPOS8(ip+1, ipIndex+1);
+        ADDPOS8(ip+2, ipIndex+2);
+        ADDPOS4(ip+1, ipIndex+1);
+
+        /* encode */
+        {   BYTE* const saved_op = op;
+            /* LZ4HC_encodeSequence always updates @op; on success, it updates @ip and @anchor */
+            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                    (int)matchLength, (int)matchDistance,
+                    limit, oend) ) {
+                op = saved_op;  /* restore @op value before failed LZ4HC_encodeSequence */
+                goto _lz4mid_dest_overflow;
+            }
+        }
+
+        /* fill table with end of match */
+        {   U32 endMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
+            U32 pos_m2 = endMatchIdx - 2;
+            if (pos_m2 < ilimitIdx) {
+                if (likely(ip - prefixPtr > 5)) {
+                    ADDPOS8(ip-5, endMatchIdx - 5);
+                }
+                ADDPOS8(ip-3, endMatchIdx - 3);
+                ADDPOS8(ip-2, endMatchIdx - 2);
+                ADDPOS4(ip-2, endMatchIdx - 2);
+                ADDPOS4(ip-1, endMatchIdx - 1);
+            }
+        }
+    }
+
+_lz4mid_last_literals:
+    /* Encode Last Literals */
+    {   size_t lastRunSize = (size_t)(iend - anchor);  /* literals */
+        size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;
+        size_t const totalSize = 1 + llAdd + lastRunSize;
+        if (limit == fillOutput) oend += LASTLITERALS;  /* restore correct value */
+        if (limit && (op + totalSize > oend)) {
+            if (limit == limitedOutput) return 0;  /* not enough space in @dst */
+            /* adapt lastRunSize to fill 'dest' */
+            lastRunSize  = (size_t)(oend - op) - 1 /*token*/;
+            llAdd = (lastRunSize + 256 - RUN_MASK) / 256;
+            lastRunSize -= llAdd;
+        }
+        DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize);
+        ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */
+
+        if (lastRunSize >= RUN_MASK) {
+            size_t accumulator = lastRunSize - RUN_MASK;
+            *op++ = (RUN_MASK << ML_BITS);
+            for(; accumulator >= 255 ; accumulator -= 255)
+                *op++ = 255;
+            *op++ = (BYTE) accumulator;
+        } else {
+            *op++ = (BYTE)(lastRunSize << ML_BITS);
+        }
+        assert(lastRunSize <= (size_t)(oend - op));
+        LZ4_memcpy(op, anchor, lastRunSize);
+        op += lastRunSize;
+    }
+
+    /* End */
+    DEBUGLOG(5, "compressed %i bytes into %i bytes", *srcSizePtr, (int)((char*)op - dst));
+    assert(ip >= (const BYTE*)src);
+    assert(ip <= iend);
+    *srcSizePtr = (int)(ip - (const BYTE*)src);
+    assert((char*)op >= dst);
+    assert(op <= oend);
+    assert((char*)op - dst < INT_MAX);
+    return (int)((char*)op - dst);
+
+_lz4mid_dest_overflow:
+    if (limit == fillOutput) {
+        /* Assumption : @ip, @anchor, @optr and @matchLength must be set correctly */
+        size_t const ll = (size_t)(ip - anchor);
+        size_t const ll_addbytes = (ll + 240) / 255;
+        size_t const ll_totalCost = 1 + ll_addbytes + ll;
+        BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */
+        DEBUGLOG(6, "Last sequence is overflowing : %u literals, %u remaining space",
+                (unsigned)ll, (unsigned)(oend-op));
+        if (op + ll_totalCost <= maxLitPos) {
+            /* ll validated; now adjust match length */
+            size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));
+            size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);
+            assert(maxMlSize < INT_MAX);
+            if ((size_t)matchLength > maxMlSize) matchLength= (unsigned)maxMlSize;
+            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + matchLength >= MFLIMIT) {
+            DEBUGLOG(6, "Let's encode a last sequence (ll=%u, ml=%u)", (unsigned)ll, matchLength);
+                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                        (int)matchLength, (int)matchDistance,
+                        notLimited, oend);
+        }   }
+        DEBUGLOG(6, "Let's finish with a run of literals (%u bytes left)", (unsigned)(oend-op));
+        goto _lz4mid_last_literals;
+    }
+    /* compression failed */
+    return 0;
+}
+
+
+/**************************************
+*  HC Compression - Search
+**************************************/
+
 /* Update chains up to ip (excluded) */
 LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
 {
@@ -140,23 +801,6 @@
     hc4->nextToUpdate = target;
 }
 
-/** LZ4HC_countBack() :
- * @return : negative value, nb of common bytes before ip/match */
-LZ4_FORCE_INLINE
-int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
-                    const BYTE* const iMin, const BYTE* const mMin)
-{
-    int back = 0;
-    int const min = (int)MAX(iMin - ip, mMin - match);
-    assert(min <= 0);
-    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
-    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
-    while ( (back > min)
-         && (ip[back-1] == match[back-1]) )
-            back--;
-    return back;
-}
-
 #if defined(_MSC_VER)
 #  define LZ4HC_rotl32(x,r) _rotl(x,r)
 #else
@@ -236,22 +880,21 @@
 typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;
 typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;
 
-LZ4_FORCE_INLINE int
+
+LZ4_FORCE_INLINE LZ4HC_match_t
 LZ4HC_InsertAndGetWiderMatch (
         LZ4HC_CCtx_internal* const hc4,
         const BYTE* const ip,
         const BYTE* const iLowLimit, const BYTE* const iHighLimit,
         int longest,
-        const BYTE** matchpos,
-        const BYTE** startpos,
         const int maxNbAttempts,
         const int patternAnalysis, const int chainSwap,
         const dictCtx_directive dict,
         const HCfavor_e favorDecSpeed)
 {
     U16* const chainTable = hc4->chainTable;
-    U32* const HashTable = hc4->hashTable;
-    const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx;
+    U32* const hashTable = hc4->hashTable;
+    const LZ4HC_CCtx_internal* const dictCtx = hc4->dictCtx;
     const BYTE* const prefixPtr = hc4->prefixStart;
     const U32 prefixIdx = hc4->dictLimit;
     const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
@@ -267,22 +910,24 @@
     U32 matchIndex;
     repeat_state_e repeat = rep_untested;
     size_t srcPatternLength = 0;
+    int offset = 0, sBack = 0;
 
     DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
     /* First Match */
-    LZ4HC_Insert(hc4, ip);
-    matchIndex = HashTable[LZ4HC_hashPtr(ip)];
-    DEBUGLOG(7, "First match at index %u / %u (lowestMatchIndex)",
-                matchIndex, lowestMatchIndex);
+    LZ4HC_Insert(hc4, ip);  /* insert all prior positions up to ip (excluded) */
+    matchIndex = hashTable[LZ4HC_hashPtr(ip)];
+    DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)",
+                ipIndex, matchIndex, lowestMatchIndex);
 
     while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0)) {
         int matchLength=0;
         nbAttempts--;
         assert(matchIndex < ipIndex);
         if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
-            /* do nothing */
+            /* do nothing:
+             * favorDecSpeed intentionally skips matches with offset < 8 */
         } else if (matchIndex >= prefixIdx) {   /* within current Prefix */
-            const BYTE* const matchPtr = prefixPtr + matchIndex - prefixIdx;
+            const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx);
             assert(matchPtr < ip);
             assert(longest >= 1);
             if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
@@ -292,10 +937,11 @@
                     matchLength -= back;
                     if (matchLength > longest) {
                         longest = matchLength;
-                        *matchpos = matchPtr + back;
-                        *startpos = ip + back;
+                        offset = (int)(ipIndex - matchIndex);
+                        sBack = back;
+                        DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back);
             }   }   }
-        } else {   /* lowestMatchIndex <= matchIndex < dictLimit */
+        } else {   /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */
             const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx);
             assert(matchIndex >= dictIdx);
             if ( likely(matchIndex <= prefixIdx - 4)
@@ -310,8 +956,9 @@
                 matchLength -= back;
                 if (matchLength > longest) {
                     longest = matchLength;
-                    *matchpos = prefixPtr - prefixIdx + matchIndex + back;   /* virtual pos, relative to ip, to retrieve offset */
-                    *startpos = ip + back;
+                    offset = (int)(ipIndex - matchIndex);
+                    sBack = back;
+                    DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back);
         }   }   }
 
         if (chainSwap && matchLength==longest) {   /* better match => select a better chain */
@@ -344,6 +991,7 @@
                 if (repeat == rep_untested) {
                     if ( ((pattern & 0xFFFF) == (pattern >> 16))
                       &  ((pattern & 0xFF)   == (pattern >> 24)) ) {
+                        DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24);
                         repeat = rep_confirmed;
                         srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
                     } else {
@@ -352,7 +1000,7 @@
                 if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
                   && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx) ) {
                     const int extDict = matchCandidateIdx < prefixIdx;
-                    const BYTE* const matchPtr = (extDict ? dictStart - dictIdx : prefixPtr - prefixIdx) + matchCandidateIdx;
+                    const BYTE* const matchPtr = extDict ? dictStart + (matchCandidateIdx - dictIdx) : prefixPtr + (matchCandidateIdx - prefixIdx);
                     if (LZ4_read32(matchPtr) == pattern) {  /* good candidate */
                         const BYTE* const iLimit = extDict ? dictEnd : iHighLimit;
                         size_t forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
@@ -398,8 +1046,9 @@
                                             if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break;
                                             assert(maxML < 2 GB);
                                             longest = (int)maxML;
-                                            *matchpos = prefixPtr - prefixIdx + matchIndex;   /* virtual pos, relative to ip, to retrieve offset */
-                                            *startpos = ip;
+                                            offset = (int)(ipIndex - matchIndex);
+                                            assert(sBack == 0);
+                                            DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset);
                                         }
                                         {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
                                             if (distToNextPattern > matchIndex) break;  /* avoid overflow */
@@ -416,11 +1065,12 @@
 
     if ( dict == usingDictCtxHc
       && nbAttempts > 0
-      && ipIndex - lowestMatchIndex < LZ4_DISTANCE_MAX) {
+      && withinStartDistance) {
         size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
         U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
         assert(dictEndOffset <= 1 GB);
         matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;
+        if (dictMatchIndex>0) DEBUGLOG(7, "dictEndOffset = %zu, dictMatchIndex = %u => relative matchIndex = %i", dictEndOffset, dictMatchIndex, (int)dictMatchIndex - (int)dictEndOffset);
         while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
             const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + dictMatchIndex;
 
@@ -434,8 +1084,9 @@
                 mlt -= back;
                 if (mlt > longest) {
                     longest = mlt;
-                    *matchpos = prefixPtr - prefixIdx + matchIndex + back;
-                    *startpos = ip + back;
+                    offset = (int)(ipIndex - matchIndex);
+                    sBack = back;
+                    DEBUGLOG(7, "found match of length %i within extDictCtx", longest);
             }   }
 
             {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);
@@ -443,112 +1094,29 @@
                 matchIndex -= nextOffset;
     }   }   }
 
-    return longest;
+    {   LZ4HC_match_t md;
+        assert(longest >= 0);
+        md.len = longest;
+        md.off = offset;
+        md.back = sBack;
+        return md;
+    }
 }
 
-LZ4_FORCE_INLINE int
+LZ4_FORCE_INLINE LZ4HC_match_t
 LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4,   /* Index table will be updated */
                        const BYTE* const ip, const BYTE* const iLimit,
-                       const BYTE** matchpos,
                        const int maxNbAttempts,
                        const int patternAnalysis,
                        const dictCtx_directive dict)
 {
-    const BYTE* uselessPtr = ip;
+    DEBUGLOG(7, "LZ4HC_InsertAndFindBestMatch");
     /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
      * but this won't be the case here, as we define iLowLimit==ip,
      * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
-    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
+    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
 }
 
-/* LZ4HC_encodeSequence() :
- * @return : 0 if ok,
- *           1 if buffer issue detected */
-LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
-    const BYTE** _ip,
-    BYTE** _op,
-    const BYTE** _anchor,
-    int matchLength,
-    const BYTE* const match,
-    limitedOutput_directive limit,
-    BYTE* oend)
-{
-#define ip      (*_ip)
-#define op      (*_op)
-#define anchor  (*_anchor)
-
-    size_t length;
-    BYTE* const token = op++;
-
-#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
-    static const BYTE* start = NULL;
-    static U32 totalCost = 0;
-    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start);
-    U32 const ll = (U32)(ip - anchor);
-    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
-    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
-    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
-    if (start==NULL) start = anchor;  /* only works for single segment */
-    /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
-    DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5u, cost:%4u + %5u",
-                pos,
-                (U32)(ip - anchor), matchLength, (U32)(ip-match),
-                cost, totalCost);
-    totalCost += cost;
-#endif
-
-    /* Encode Literal length */
-    length = (size_t)(ip - anchor);
-    LZ4_STATIC_ASSERT(notLimited == 0);
-    /* Check output limit */
-    if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) {
-        DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
-                (int)length, (int)(oend - op));
-        return 1;
-    }
-    if (length >= RUN_MASK) {
-        size_t len = length - RUN_MASK;
-        *token = (RUN_MASK << ML_BITS);
-        for(; len >= 255 ; len -= 255) *op++ = 255;
-        *op++ = (BYTE)len;
-    } else {
-        *token = (BYTE)(length << ML_BITS);
-    }
-
-    /* Copy Literals */
-    LZ4_wildCopy8(op, anchor, op + length);
-    op += length;
-
-    /* Encode Offset */
-    assert( (ip - match) <= LZ4_DISTANCE_MAX );   /* note : consider providing offset as a value, rather than as a pointer difference */
-    LZ4_writeLE16(op, (U16)(ip - match)); op += 2;
-
-    /* Encode MatchLength */
-    assert(matchLength >= MINMATCH);
-    length = (size_t)matchLength - MINMATCH;
-    if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) {
-        DEBUGLOG(6, "Not enough room to write match length");
-        return 1;   /* Check output limit */
-    }
-    if (length >= ML_MASK) {
-        *token += ML_MASK;
-        length -= ML_MASK;
-        for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; }
-        if (length >= 255) { length -= 255; *op++ = 255; }
-        *op++ = (BYTE)length;
-    } else {
-        *token += (BYTE)(length);
-    }
-
-    /* Prepare next loop */
-    ip += matchLength;
-    anchor = ip;
-
-    return 0;
-}
-#undef ip
-#undef op
-#undef anchor
 
 LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
     LZ4HC_CCtx_internal* const ctx,
@@ -574,127 +1142,130 @@
     BYTE* op = (BYTE*) dest;
     BYTE* oend = op + maxOutputSize;
 
-    int   ml0, ml, ml2, ml3;
     const BYTE* start0;
-    const BYTE* ref0;
-    const BYTE* ref = NULL;
     const BYTE* start2 = NULL;
-    const BYTE* ref2 = NULL;
     const BYTE* start3 = NULL;
-    const BYTE* ref3 = NULL;
+    LZ4HC_match_t m0, m1, m2, m3;
+    const LZ4HC_match_t nomatch = {0, 0, 0};
 
     /* init */
+    DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict);
     *srcSizePtr = 0;
     if (limit == fillOutput) oend -= LASTLITERALS;                  /* Hack for support LZ4 format restriction */
     if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */
 
     /* Main Loop */
     while (ip <= mflimit) {
-        ml = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict);
-        if (ml<MINMATCH) { ip++; continue; }
+        m1 = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, maxNbAttempts, patternAnalysis, dict);
+        if (m1.len<MINMATCH) { ip++; continue; }
 
         /* saved, in case we would skip too much */
-        start0 = ip; ref0 = ref; ml0 = ml;
+        start0 = ip; m0 = m1;
 
 _Search2:
-        if (ip+ml <= mflimit) {
-            ml2 = LZ4HC_InsertAndGetWiderMatch(ctx,
-                            ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2,
+        DEBUGLOG(7, "_Search2 (currently found match of size %i)", m1.len);
+        if (ip+m1.len <= mflimit) {
+            start2 = ip + m1.len - 2;
+            m2 = LZ4HC_InsertAndGetWiderMatch(ctx,
+                            start2, ip + 0, matchlimit, m1.len,
                             maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
+            start2 += m2.back;
         } else {
-            ml2 = ml;
+            m2 = nomatch;  /* do not search further */
         }
 
-        if (ml2 == ml) { /* No better match => encode ML1 */
+        if (m2.len <= m1.len) { /* No better match => encode ML1 immediately */
             optr = op;
-            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
+            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                    m1.len, m1.off,
+                    limit, oend) )
+                goto _dest_overflow;
             continue;
         }
 
         if (start0 < ip) {   /* first match was skipped at least once */
-            if (start2 < ip + ml0) {  /* squeezing ML1 between ML0(original ML1) and ML2 */
-                ip = start0; ref = ref0; ml = ml0;  /* restore initial ML1 */
+            if (start2 < ip + m0.len) {  /* squeezing ML1 between ML0(original ML1) and ML2 */
+                ip = start0; m1 = m0;  /* restore initial Match1 */
         }   }
 
         /* Here, start0==ip */
         if ((start2 - ip) < 3) {  /* First Match too small : removed */
-            ml = ml2;
             ip = start2;
-            ref =ref2;
+            m1 = m2;
             goto _Search2;
         }
 
 _Search3:
-        /* At this stage, we have :
-        *  ml2 > ml1, and
-        *  ip1+3 <= ip2 (usually < ip1+ml1) */
         if ((start2 - ip) < OPTIMAL_ML) {
             int correction;
-            int new_ml = ml;
+            int new_ml = m1.len;
             if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
-            if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
+            if (ip+new_ml > start2 + m2.len - MINMATCH)
+                new_ml = (int)(start2 - ip) + m2.len - MINMATCH;
             correction = new_ml - (int)(start2 - ip);
             if (correction > 0) {
                 start2 += correction;
-                ref2 += correction;
-                ml2 -= correction;
+                m2.len -= correction;
             }
         }
-        /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
 
-        if (start2 + ml2 <= mflimit) {
-            ml3 = LZ4HC_InsertAndGetWiderMatch(ctx,
-                            start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3,
+        if (start2 + m2.len <= mflimit) {
+            start3 = start2 + m2.len - 3;
+            m3 = LZ4HC_InsertAndGetWiderMatch(ctx,
+                            start3, start2, matchlimit, m2.len,
                             maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
+            start3 += m3.back;
         } else {
-            ml3 = ml2;
+            m3 = nomatch;  /* do not search further */
         }
 
-        if (ml3 == ml2) {  /* No better match => encode ML1 and ML2 */
+        if (m3.len <= m2.len) {  /* No better match => encode ML1 and ML2 */
             /* ip & ref are known; Now for ml */
-            if (start2 < ip+ml)  ml = (int)(start2 - ip);
+            if (start2 < ip+m1.len) m1.len = (int)(start2 - ip);
             /* Now, encode 2 sequences */
             optr = op;
-            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
+            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                    m1.len, m1.off,
+                    limit, oend) )
+                goto _dest_overflow;
             ip = start2;
             optr = op;
-            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml2, ref2, limit, oend)) {
-                ml  = ml2;
-                ref = ref2;
+            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                    m2.len, m2.off,
+                    limit, oend) ) {
+                m1 = m2;
                 goto _dest_overflow;
             }
             continue;
         }
 
-        if (start3 < ip+ml+3) {  /* Not enough space for match 2 : remove it */
-            if (start3 >= (ip+ml)) {  /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
-                if (start2 < ip+ml) {
-                    int correction = (int)(ip+ml - start2);
+        if (start3 < ip+m1.len+3) {  /* Not enough space for match 2 : remove it */
+            if (start3 >= (ip+m1.len)) {  /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
+                if (start2 < ip+m1.len) {
+                    int correction = (int)(ip+m1.len - start2);
                     start2 += correction;
-                    ref2 += correction;
-                    ml2 -= correction;
-                    if (ml2 < MINMATCH) {
+                    m2.len -= correction;
+                    if (m2.len < MINMATCH) {
                         start2 = start3;
-                        ref2 = ref3;
-                        ml2 = ml3;
+                        m2 = m3;
                     }
                 }
 
                 optr = op;
-                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
+                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                        m1.len, m1.off,
+                        limit, oend) )
+                    goto _dest_overflow;
                 ip  = start3;
-                ref = ref3;
-                ml  = ml3;
+                m1 = m3;
 
                 start0 = start2;
-                ref0 = ref2;
-                ml0 = ml2;
+                m0 = m2;
                 goto _Search2;
             }
 
             start2 = start3;
-            ref2 = ref3;
-            ml2 = ml3;
+            m2 = m3;
             goto _Search3;
         }
 
@@ -703,29 +1274,32 @@
         * let's write the first one ML1.
         * ip & ref are known; Now decide ml.
         */
-        if (start2 < ip+ml) {
+        if (start2 < ip+m1.len) {
             if ((start2 - ip) < OPTIMAL_ML) {
                 int correction;
-                if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
-                if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
-                correction = ml - (int)(start2 - ip);
+                if (m1.len > OPTIMAL_ML) m1.len = OPTIMAL_ML;
+                if (ip + m1.len > start2 + m2.len - MINMATCH)
+                    m1.len = (int)(start2 - ip) + m2.len - MINMATCH;
+                correction = m1.len - (int)(start2 - ip);
                 if (correction > 0) {
                     start2 += correction;
-                    ref2 += correction;
-                    ml2 -= correction;
+                    m2.len -= correction;
                 }
             } else {
-                ml = (int)(start2 - ip);
+                m1.len = (int)(start2 - ip);
             }
         }
         optr = op;
-        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
+        if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
+                m1.len, m1.off,
+                limit, oend) )
+            goto _dest_overflow;
 
         /* ML2 becomes ML1 */
-        ip = start2; ref = ref2; ml = ml2;
+        ip = start2; m1 = m2;
 
         /* ML3 becomes ML2 */
-        start2 = start3; ref2 = ref3; ml2 = ml3;
+        start2 = start3; m2 = m3;
 
         /* let's find a new ML3 */
         goto _Search3;
@@ -765,7 +1339,7 @@
 
 _dest_overflow:
     if (limit == fillOutput) {
-        /* Assumption : ip, anchor, ml and ref must be set correctly */
+        /* Assumption : @ip, @anchor, @optr and @m1 must be set correctly */
         size_t const ll = (size_t)(ip - anchor);
         size_t const ll_addbytes = (ll + 240) / 255;
         size_t const ll_totalCost = 1 + ll_addbytes + ll;
@@ -776,10 +1350,10 @@
             /* ll validated; now adjust match length */
             size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));
             size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);
-            assert(maxMlSize < INT_MAX); assert(ml >= 0);
-            if ((size_t)ml > maxMlSize) ml = (int)maxMlSize;
-            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ml >= MFLIMIT) {
-                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, notLimited, oend);
+            assert(maxMlSize < INT_MAX); assert(m1.len >= 0);
+            if ((size_t)m1.len > maxMlSize) m1.len = (int)maxMlSize;
+            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + m1.len >= MFLIMIT) {
+                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, notLimited, oend);
         }   }
         goto _last_literals;
     }
@@ -796,54 +1370,34 @@
     const dictCtx_directive dict,
     const HCfavor_e favorDecSpeed);
 
-
-LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (
-    LZ4HC_CCtx_internal* const ctx,
-    const char* const src,
-    char* const dst,
-    int* const srcSizePtr,
-    int const dstCapacity,
-    int cLevel,
-    const limitedOutput_directive limit,
-    const dictCtx_directive dict
-    )
+LZ4_FORCE_INLINE int
+LZ4HC_compress_generic_internal (
+            LZ4HC_CCtx_internal* const ctx,
+            const char* const src,
+            char* const dst,
+            int* const srcSizePtr,
+            int const dstCapacity,
+            int cLevel,
+            const limitedOutput_directive limit,
+            const dictCtx_directive dict
+            )
 {
-    typedef enum { lz4hc, lz4opt } lz4hc_strat_e;
-    typedef struct {
-        lz4hc_strat_e strat;
-        int nbSearches;
-        U32 targetLength;
-    } cParams_t;
-    static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = {
-        { lz4hc,     2, 16 },  /* 0, unused */
-        { lz4hc,     2, 16 },  /* 1, unused */
-        { lz4hc,     2, 16 },  /* 2, unused */
-        { lz4hc,     4, 16 },  /* 3 */
-        { lz4hc,     8, 16 },  /* 4 */
-        { lz4hc,    16, 16 },  /* 5 */
-        { lz4hc,    32, 16 },  /* 6 */
-        { lz4hc,    64, 16 },  /* 7 */
-        { lz4hc,   128, 16 },  /* 8 */
-        { lz4hc,   256, 16 },  /* 9 */
-        { lz4opt,   96, 64 },  /*10==LZ4HC_CLEVEL_OPT_MIN*/
-        { lz4opt,  512,128 },  /*11 */
-        { lz4opt,16384,LZ4_OPT_NUM },  /* 12==LZ4HC_CLEVEL_MAX */
-    };
-
-    DEBUGLOG(4, "LZ4HC_compress_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)",
-                ctx, src, *srcSizePtr, limit);
+    DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d)",
+                src, *srcSizePtr);
 
     if (limit == fillOutput && dstCapacity < 1) return 0;   /* Impossible to store anything */
-    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;    /* Unsupported input size (too large or negative) */
+    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;  /* Unsupported input size (too large or negative) */
 
     ctx->end += *srcSizePtr;
-    if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT;   /* note : convention is different from lz4frame, maybe something to review */
-    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
-    {   cParams_t const cParam = clTable[cLevel];
+    {   cParams_t const cParam = LZ4HC_getCLevelParams(cLevel);
         HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
         int result;
 
-        if (cParam.strat == lz4hc) {
+        if (cParam.strat == lz4mid) {
+            result = LZ4MID_compress(ctx,
+                                src, dst, srcSizePtr, dstCapacity,
+                                limit, dict);
+        } else if (cParam.strat == lz4hc) {
             result = LZ4HC_compress_hashChain(ctx,
                                 src, dst, srcSizePtr, dstCapacity,
                                 cParam.nbSearches, limit, dict);
@@ -852,7 +1406,7 @@
             result = LZ4HC_compress_optimal(ctx,
                                 src, dst, srcSizePtr, dstCapacity,
                                 cParam.nbSearches, cParam.targetLength, limit,
-                                cLevel == LZ4HC_CLEVEL_MAX,   /* ultra mode */
+                                cLevel >= LZ4HC_CLEVEL_MAX,   /* ultra mode */
                                 dict, favor);
         }
         if (result <= 0) ctx->dirty = 1;
@@ -877,6 +1431,13 @@
     return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
 }
 
+static int isStateCompatible(const LZ4HC_CCtx_internal* ctx1, const LZ4HC_CCtx_internal* ctx2)
+{
+    int const isMid1 = LZ4HC_getCLevelParams(ctx1->compressionLevel).strat == lz4mid;
+    int const isMid2 = LZ4HC_getCLevelParams(ctx2->compressionLevel).strat == lz4mid;
+    return !(isMid1 ^ isMid2);
+}
+
 static int
 LZ4HC_compress_generic_dictCtx (
         LZ4HC_CCtx_internal* const ctx,
@@ -893,7 +1454,7 @@
     if (position >= 64 KB) {
         ctx->dictCtx = NULL;
         return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
-    } else if (position == 0 && *srcSizePtr > 4 KB) {
+    } else if (position == 0 && *srcSizePtr > 4 KB && isStateCompatible(ctx, ctx->dictCtx)) {
         LZ4_memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));
         LZ4HC_setExternalDict(ctx, (const BYTE *)src);
         ctx->compressionLevel = (short)cLevel;
@@ -965,6 +1526,7 @@
     LZ4_streamHC_t state;
     LZ4_streamHC_t* const statePtr = &state;
 #endif
+    DEBUGLOG(5, "LZ4_compress_HC")
     cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);
 #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
     FREEMEM(statePtr);
@@ -1032,18 +1594,16 @@
 
 void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
 {
-    DEBUGLOG(4, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
-    if (LZ4_streamHCPtr->internal_donotuse.dirty) {
+    LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse;
+    DEBUGLOG(5, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
+    if (s->dirty) {
         LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
     } else {
-        /* preserve end - prefixStart : can trigger clearTable's threshold */
-        if (LZ4_streamHCPtr->internal_donotuse.end != NULL) {
-            LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.prefixStart;
-        } else {
-            assert(LZ4_streamHCPtr->internal_donotuse.prefixStart == NULL);
-        }
-        LZ4_streamHCPtr->internal_donotuse.prefixStart = NULL;
-        LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
+        assert(s->end >= s->prefixStart);
+        s->dictLimit += (U32)(s->end - s->prefixStart);
+        s->prefixStart = NULL;
+        s->end = NULL;
+        s->dictCtx = NULL;
     }
     LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
 }
@@ -1067,7 +1627,9 @@
               const char* dictionary, int dictSize)
 {
     LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
-    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d)", LZ4_streamHCPtr, dictionary, dictSize);
+    cParams_t cp;
+    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d, clevel=%d)", LZ4_streamHCPtr, dictionary, dictSize, ctxPtr->compressionLevel);
+    assert(dictSize >= 0);
     assert(LZ4_streamHCPtr != NULL);
     if (dictSize > 64 KB) {
         dictionary += (size_t)dictSize - 64 KB;
@@ -1077,10 +1639,15 @@
     {   int const cLevel = ctxPtr->compressionLevel;
         LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
         LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
+        cp = LZ4HC_getCLevelParams(cLevel);
     }
     LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
     ctxPtr->end = (const BYTE*)dictionary + dictSize;
-    if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
+    if (cp.strat == lz4mid) {
+        LZ4MID_fillHTable (ctxPtr, dictionary, (size_t)dictSize);
+    } else {
+        if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
+    }
     return dictSize;
 }
 
@@ -1093,8 +1660,10 @@
 static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
 {
     DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
-    if (ctxPtr->end >= ctxPtr->prefixStart + 4)
-        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);   /* Referencing remaining dictionary content */
+    if ( (ctxPtr->end >= ctxPtr->prefixStart + 4)
+      && (LZ4HC_getCLevelParams(ctxPtr->compressionLevel).strat != lz4mid) ) {
+        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);  /* Referencing remaining dictionary content */
+    }
 
     /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
     ctxPtr->lowLimit  = ctxPtr->dictLimit;
@@ -1119,7 +1688,8 @@
                 LZ4_streamHCPtr, src, *srcSizePtr, limit);
     assert(ctxPtr != NULL);
     /* auto-init if forgotten */
-    if (ctxPtr->prefixStart == NULL) LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
+    if (ctxPtr->prefixStart == NULL)
+        LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
 
     /* Check overflow */
     if ((size_t)(ctxPtr->end - ctxPtr->prefixStart) + ctxPtr->dictLimit > 2 GB) {
@@ -1140,7 +1710,8 @@
             if (sourceEnd > dictEnd) sourceEnd = dictEnd;
             ctxPtr->lowLimit += (U32)(sourceEnd - ctxPtr->dictStart);
             ctxPtr->dictStart += (U32)(sourceEnd - ctxPtr->dictStart);
-            if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) {
+            /* invalidate dictionary is it's too small */
+            if (ctxPtr->dictLimit - ctxPtr->lowLimit < LZ4HC_HASHSIZE) {
                 ctxPtr->lowLimit = ctxPtr->dictLimit;
                 ctxPtr->dictStart = ctxPtr->prefixStart;
     }   }   }
@@ -1150,6 +1721,7 @@
 
 int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
 {
+    DEBUGLOG(5, "LZ4_compress_HC_continue");
     if (dstCapacity < LZ4_compressBound(srcSize))
         return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput);
     else
@@ -1162,7 +1734,6 @@
 }
 
 
-
 /* LZ4_saveDictHC :
  * save history content
  * into a user-provided buffer
@@ -1179,10 +1750,10 @@
     if (dictSize > prefixSize) dictSize = prefixSize;
     if (safeBuffer == NULL) assert(dictSize == 0);
     if (dictSize > 0)
-        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, dictSize);
+        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize);
     {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit;
-        streamPtr->end = (const BYTE*)safeBuffer + dictSize;
-        streamPtr->prefixStart = streamPtr->end - dictSize;
+        streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize;
+        streamPtr->prefixStart = (const BYTE*)safeBuffer;
         streamPtr->dictLimit = endIndex - (U32)dictSize;
         streamPtr->lowLimit = endIndex - (U32)dictSize;
         streamPtr->dictStart = streamPtr->prefixStart;
@@ -1193,75 +1764,6 @@
 }
 
 
-/***************************************************
-*  Deprecated Functions
-***************************************************/
-
-/* These functions currently generate deprecation warnings */
-
-/* Wrappers for deprecated compression functions */
-int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
-int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
-int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
-int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
-int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
-int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
-int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
-int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
-int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
-int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
-
-
-/* Deprecated streaming functions */
-int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); }
-
-/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
- * @return : 0 on success, !=0 if error */
-int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
-{
-    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
-    if (hc4 == NULL) return 1;   /* init failed */
-    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
-    return 0;
-}
-
-#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
-void* LZ4_createHC (const char* inputBuffer)
-{
-    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
-    if (hc4 == NULL) return NULL;   /* not enough memory */
-    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
-    return hc4;
-}
-
-int LZ4_freeHC (void* LZ4HC_Data)
-{
-    if (!LZ4HC_Data) return 0;  /* support free on NULL */
-    FREEMEM(LZ4HC_Data);
-    return 0;
-}
-#endif
-
-int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
-{
-    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);
-}
-
-int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
-{
-    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);
-}
-
-char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
-{
-    LZ4_streamHC_t* const ctx = (LZ4_streamHC_t*)LZ4HC_Data;
-    const BYTE* bufferStart = ctx->internal_donotuse.prefixStart - ctx->internal_donotuse.dictLimit + ctx->internal_donotuse.lowLimit;
-    LZ4_resetStreamHC_fast(ctx, ctx->internal_donotuse.compressionLevel);
-    /* avoid const char * -> char * conversion warning :( */
-    return (char*)(uptrval)bufferStart;
-}
-
-
 /* ================================================
  *  LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])
  * ===============================================*/
@@ -1282,7 +1784,6 @@
     return price;
 }
 
-
 /* requires mlen >= MINMATCH */
 LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
 {
@@ -1298,12 +1799,6 @@
     return price;
 }
 
-
-typedef struct {
-    int off;
-    int len;
-} LZ4HC_match_t;
-
 LZ4_FORCE_INLINE LZ4HC_match_t
 LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,
                       const BYTE* ip, const BYTE* const iHighLimit,
@@ -1311,19 +1806,17 @@
                       const dictCtx_directive dict,
                       const HCfavor_e favorDecSpeed)
 {
-    LZ4HC_match_t match = { 0 , 0 };
-    const BYTE* matchPtr = NULL;
+    LZ4HC_match_t const match0 = { 0 , 0, 0 };
     /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
      * but this won't be the case here, as we define iLowLimit==ip,
-     * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
-    int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
-    if (matchLength <= minLen) return match;
+    ** so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
+    LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
+    assert(md.back == 0);
+    if (md.len <= minLen) return match0;
     if (favorDecSpeed) {
-        if ((matchLength>18) & (matchLength<=36)) matchLength=18;   /* favor shortcut */
+        if ((md.len>18) & (md.len<=36)) md.len=18;   /* favor dec.speed (shortcut) */
     }
-    match.len = matchLength;
-    match.off = (int)(ip-matchPtr);
-    return match;
+    return md;
 }
 
 
@@ -1356,7 +1849,7 @@
     BYTE* opSaved = (BYTE*) dst;
     BYTE* oend = op + dstCapacity;
     int ovml = MINMATCH;  /* overflow - last sequence */
-    const BYTE* ovref = NULL;
+    int ovoff = 0;
 
     /* init */
 #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
@@ -1379,11 +1872,10 @@
          if ((size_t)firstMatch.len > sufficient_len) {
              /* good enough solution : immediate encoding */
              int const firstML = firstMatch.len;
-             const BYTE* const matchPos = ip - firstMatch.off;
              opSaved = op;
-             if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, matchPos, limit, oend) ) {  /* updates ip, op and anchor */
+             if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, firstMatch.off, limit, oend) ) {  /* updates ip, op and anchor */
                  ovml = firstML;
-                 ovref = matchPos;
+                 ovoff = firstMatch.off;
                  goto _dest_overflow;
              }
              continue;
@@ -1401,11 +1893,11 @@
                              rPos, cost, opt[rPos].litlen);
          }   }
          /* set prices using initial match */
-         {   int mlen = MINMATCH;
-             int const matchML = firstMatch.len;   /* necessarily < sufficient_len < LZ4_OPT_NUM */
+         {   int const matchML = firstMatch.len;   /* necessarily < sufficient_len < LZ4_OPT_NUM */
              int const offset = firstMatch.off;
+             int mlen;
              assert(matchML < LZ4_OPT_NUM);
-             for ( ; mlen <= matchML ; mlen++) {
+             for (mlen = MINMATCH ; mlen <= matchML ; mlen++) {
                  int const cost = LZ4HC_sequencePrice(llen, mlen);
                  opt[mlen].mlen = mlen;
                  opt[mlen].off = offset;
@@ -1557,9 +2049,9 @@
                  assert(ml >= MINMATCH);
                  assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
                  opSaved = op;
-                 if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ip - offset, limit, oend) ) {  /* updates ip, op and anchor */
+                 if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) {  /* updates ip, op and anchor */
                      ovml = ml;
-                     ovref = ip - offset;
+                     ovoff = offset;
                      goto _dest_overflow;
          }   }   }
      }  /* while (ip <= mflimit) */
@@ -1618,14 +2110,83 @@
          if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ovml >= MFLIMIT) {
              DEBUGLOG(6, "Space to end : %i + ml (%i)", (int)((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1), ovml);
              DEBUGLOG(6, "Before : ip = %p, anchor = %p", ip, anchor);
-             LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovref, notLimited, oend);
+             LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovoff, notLimited, oend);
              DEBUGLOG(6, "After : ip = %p, anchor = %p", ip, anchor);
      }   }
      goto _last_literals;
 }
 _return_label:
 #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
-     FREEMEM(opt);
+     if (opt) FREEMEM(opt);
 #endif
      return retval;
 }
+
+
+/***************************************************
+*  Deprecated Functions
+***************************************************/
+
+/* These functions currently generate deprecation warnings */
+
+/* Wrappers for deprecated compression functions */
+int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
+int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
+int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
+int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
+int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
+int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
+int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
+int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
+int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
+int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
+
+
+/* Deprecated streaming functions */
+int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); }
+
+/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
+ * @return : 0 on success, !=0 if error */
+int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
+{
+    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
+    if (hc4 == NULL) return 1;   /* init failed */
+    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
+    return 0;
+}
+
+#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
+void* LZ4_createHC (const char* inputBuffer)
+{
+    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
+    if (hc4 == NULL) return NULL;   /* not enough memory */
+    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
+    return hc4;
+}
+
+int LZ4_freeHC (void* LZ4HC_Data)
+{
+    if (!LZ4HC_Data) return 0;  /* support free on NULL */
+    FREEMEM(LZ4HC_Data);
+    return 0;
+}
+#endif
+
+int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
+{
+    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);
+}
+
+int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
+{
+    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);
+}
+
+char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
+{
+    LZ4HC_CCtx_internal* const s = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse;
+    const BYTE* const bufferStart = s->prefixStart - s->dictLimit + s->lowLimit;
+    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)LZ4HC_Data, s->compressionLevel);
+    /* ugly conversion trick, required to evade (const char*) -> (char*) cast-qual warning :( */
+    return (char*)(uptrval)bufferStart;
+}
diff --git a/lib/lz4hc.h b/lib/lz4hc.h
index e937acf..992bc8c 100644
--- a/lib/lz4hc.h
+++ b/lib/lz4hc.h
@@ -44,7 +44,7 @@
 
 
 /* --- Useful constants --- */
-#define LZ4HC_CLEVEL_MIN         3
+#define LZ4HC_CLEVEL_MIN         2
 #define LZ4HC_CLEVEL_DEFAULT     9
 #define LZ4HC_CLEVEL_OPT_MIN    10
 #define LZ4HC_CLEVEL_MAX        12
@@ -126,6 +126,8 @@
 
   After reset, a first "fictional block" can be designated as initial dictionary,
   using LZ4_loadDictHC() (Optional).
+  Note: In order for LZ4_loadDictHC() to create the correct data structure,
+  it is essential to set the compression level _before_ loading the dictionary.
 
   Invoke LZ4_compress_HC_continue() to compress each successive block.
   The number of blocks is unlimited.
@@ -135,12 +137,12 @@
   It's allowed to update compression level anytime between blocks,
   using LZ4_setCompressionLevel() (experimental).
 
-  'dst' buffer should be sized to handle worst case scenarios
+ @dst buffer should be sized to handle worst case scenarios
   (see LZ4_compressBound(), it ensures compression success).
   In case of failure, the API does not guarantee recovery,
   so the state _must_ be reset.
   To ensure compression success
-  whenever `dst` buffer size cannot be made >= LZ4_compressBound(),
+  whenever @dst buffer size cannot be made >= LZ4_compressBound(),
   consider using LZ4_compress_HC_continue_destSize().
 
   Whenever previous input blocks can't be preserved unmodified in-place during compression of next blocks,
@@ -176,6 +178,34 @@
 LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize);
 
 
+/*! LZ4_attach_HC_dictionary() : stable since v1.10.0
+ *  This API allows for the efficient re-use of a static dictionary many times.
+ *
+ *  Rather than re-loading the dictionary buffer into a working context before
+ *  each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a
+ *  working LZ4_streamHC_t, this function introduces a no-copy setup mechanism,
+ *  in which the working stream references the dictionary stream in-place.
+ *
+ *  Several assumptions are made about the state of the dictionary stream.
+ *  Currently, only streams which have been prepared by LZ4_loadDictHC() should
+ *  be expected to work.
+ *
+ *  Alternatively, the provided dictionary stream pointer may be NULL, in which
+ *  case any existing dictionary stream is unset.
+ *
+ *  A dictionary should only be attached to a stream without any history (i.e.,
+ *  a stream that has just been reset).
+ *
+ *  The dictionary will remain attached to the working stream only for the
+ *  current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the
+ *  dictionary context association from the working stream. The dictionary
+ *  stream (and source buffer) must remain in-place / accessible / unchanged
+ *  through the lifetime of the stream session.
+ */
+LZ4LIB_API void
+LZ4_attach_HC_dictionary(LZ4_streamHC_t* working_stream,
+                   const LZ4_streamHC_t* dictionary_stream);
+
 
 /*^**********************************************
  * !!!!!!   STATIC LINKING ONLY   !!!!!!
@@ -204,18 +234,18 @@
 typedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal;
 struct LZ4HC_CCtx_internal
 {
-    LZ4_u32   hashTable[LZ4HC_HASHTABLESIZE];
-    LZ4_u16   chainTable[LZ4HC_MAXD];
-    const LZ4_byte* end;       /* next block here to continue on current prefix */
+    LZ4_u32 hashTable[LZ4HC_HASHTABLESIZE];
+    LZ4_u16 chainTable[LZ4HC_MAXD];
+    const LZ4_byte* end;     /* next block here to continue on current prefix */
     const LZ4_byte* prefixStart;  /* Indexes relative to this position */
     const LZ4_byte* dictStart; /* alternate reference for extDict */
-    LZ4_u32   dictLimit;       /* below that point, need extDict */
-    LZ4_u32   lowLimit;        /* below that point, no more dict */
-    LZ4_u32   nextToUpdate;    /* index from which to continue dictionary update */
-    short     compressionLevel;
-    LZ4_i8    favorDecSpeed;   /* favor decompression speed if this flag set,
-                                  otherwise, favor compression ratio */
-    LZ4_i8    dirty;           /* stream has to be fully reset if this flag is set */
+    LZ4_u32 dictLimit;       /* below that point, need extDict */
+    LZ4_u32 lowLimit;        /* below that point, no more history */
+    LZ4_u32 nextToUpdate;    /* index from which to continue dictionary update */
+    short   compressionLevel;
+    LZ4_i8  favorDecSpeed;   /* favor decompression speed if this flag set,
+                                otherwise, favor compression ratio */
+    LZ4_i8  dirty;           /* stream has to be fully reset if this flag is set */
     const LZ4HC_CCtx_internal* dictCtx;
 };
 
@@ -376,35 +406,6 @@
     int srcSize, int dstCapacity,
     int compressionLevel);
 
-/*! LZ4_attach_HC_dictionary() :
- *  This is an experimental API that allows for the efficient use of a
- *  static dictionary many times.
- *
- *  Rather than re-loading the dictionary buffer into a working context before
- *  each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a
- *  working LZ4_streamHC_t, this function introduces a no-copy setup mechanism,
- *  in which the working stream references the dictionary stream in-place.
- *
- *  Several assumptions are made about the state of the dictionary stream.
- *  Currently, only streams which have been prepared by LZ4_loadDictHC() should
- *  be expected to work.
- *
- *  Alternatively, the provided dictionary stream pointer may be NULL, in which
- *  case any existing dictionary stream is unset.
- *
- *  A dictionary should only be attached to a stream without any history (i.e.,
- *  a stream that has just been reset).
- *
- *  The dictionary will remain attached to the working stream only for the
- *  current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the
- *  dictionary context association from the working stream. The dictionary
- *  stream (and source buffer) must remain in-place / accessible / unchanged
- *  through the lifetime of the stream session.
- */
-LZ4LIB_STATIC_API void LZ4_attach_HC_dictionary(
-          LZ4_streamHC_t *working_stream,
-    const LZ4_streamHC_t *dictionary_stream);
-
 #if defined (__cplusplus)
 }
 #endif
diff --git a/lib/xxhash.c b/lib/xxhash.c
index ff28749..e132619 100644
--- a/lib/xxhash.c
+++ b/lib/xxhash.c
@@ -120,12 +120,12 @@
 /* *************************************
 *  Compiler Specific Options
 ***************************************/
-#ifdef _MSC_VER    /* Visual Studio */
+#if defined (_MSC_VER) && !defined (__clang__)    /* MSVC */
 #  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */
 #  define FORCE_INLINE static __forceinline
 #else
 #  if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
-#    ifdef __GNUC__
+#    if defined (__GNUC__) || defined (__clang__)
 #      define FORCE_INLINE static inline __attribute__((always_inline))
 #    else
 #      define FORCE_INLINE static inline
@@ -213,7 +213,7 @@
 /* *************************************
 *  Architecture Macros
 ***************************************/
-typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
+typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianness;
 
 /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */
 #ifndef XXH_CPU_LITTLE_ENDIAN
@@ -231,7 +231,7 @@
 *****************************/
 typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
 
-FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
+FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianness endian, XXH_alignment align)
 {
     if (align==XXH_unaligned)
         return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
@@ -239,7 +239,7 @@
         return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr);
 }
 
-FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)
+FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianness endian)
 {
     return XXH_readLE32_align(ptr, endian, XXH_unaligned);
 }
@@ -289,7 +289,7 @@
 
 static U32
 XXH32_finalize(U32 h32, const void* ptr, size_t len,
-                XXH_endianess endian, XXH_alignment align)
+                XXH_endianness endian, XXH_alignment align)
 
 {
     const BYTE* p = (const BYTE*)ptr;
@@ -350,7 +350,7 @@
 
 FORCE_INLINE U32
 XXH32_endian_align(const void* input, size_t len, U32 seed,
-                    XXH_endianess endian, XXH_alignment align)
+                    XXH_endianness endian, XXH_alignment align)
 {
     const BYTE* p = (const BYTE*)input;
     const BYTE* bEnd = p + len;
@@ -398,7 +398,7 @@
     XXH32_update(&state, input, len);
     return XXH32_digest(&state);
 #else
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if (XXH_FORCE_ALIGN_CHECK) {
         if ((((size_t)input) & 3) == 0) {   /* Input is 4-bytes aligned, leverage the speed benefit */
@@ -449,7 +449,7 @@
 
 
 FORCE_INLINE XXH_errorcode
-XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian)
+XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianness endian)
 {
     if (input==NULL)
 #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)
@@ -514,7 +514,7 @@
 
 XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
 {
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
         return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
@@ -524,7 +524,7 @@
 
 
 FORCE_INLINE U32
-XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)
+XXH32_digest_endian (const XXH32_state_t* state, XXH_endianness endian)
 {
     U32 h32;
 
@@ -545,7 +545,7 @@
 
 XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in)
 {
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
         return XXH32_digest_endian(state_in, XXH_littleEndian);
@@ -642,7 +642,7 @@
 }
 #endif
 
-FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
+FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianness endian, XXH_alignment align)
 {
     if (align==XXH_unaligned)
         return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
@@ -650,7 +650,7 @@
         return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr);
 }
 
-FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)
+FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianness endian)
 {
     return XXH_readLE64_align(ptr, endian, XXH_unaligned);
 }
@@ -700,7 +700,7 @@
 
 static U64
 XXH64_finalize(U64 h64, const void* ptr, size_t len,
-               XXH_endianess endian, XXH_alignment align)
+               XXH_endianness endian, XXH_alignment align)
 {
     const BYTE* p = (const BYTE*)ptr;
 
@@ -809,7 +809,7 @@
 
 FORCE_INLINE U64
 XXH64_endian_align(const void* input, size_t len, U64 seed,
-                XXH_endianess endian, XXH_alignment align)
+                XXH_endianness endian, XXH_alignment align)
 {
     const BYTE* p = (const BYTE*)input;
     const BYTE* bEnd = p + len;
@@ -861,7 +861,7 @@
     XXH64_update(&state, input, len);
     return XXH64_digest(&state);
 #else
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if (XXH_FORCE_ALIGN_CHECK) {
         if ((((size_t)input) & 7)==0) {  /* Input is aligned, let's leverage the speed advantage */
@@ -909,7 +909,7 @@
 }
 
 FORCE_INLINE XXH_errorcode
-XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian)
+XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianness endian)
 {
     if (input==NULL)
 #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)
@@ -970,7 +970,7 @@
 
 XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
 {
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
         return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
@@ -978,7 +978,7 @@
         return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
 }
 
-FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian)
+FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianness endian)
 {
     U64 h64;
 
@@ -1004,7 +1004,7 @@
 
 XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in)
 {
-    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
 
     if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
         return XXH64_digest_endian(state_in, XXH_littleEndian);
diff --git a/ossfuzz/decompress_fuzzer.c b/ossfuzz/decompress_fuzzer.c
index 490b3fd..b537af8 100644
--- a/ossfuzz/decompress_fuzzer.c
+++ b/ossfuzz/decompress_fuzzer.c
@@ -67,7 +67,7 @@
     /* Partial decompression with small prefix. */
     LZ4_decompress_safe_partial_usingDict((char const*)dataAfterDict, dst, size,
                                   dstCapacity, dstCapacity, smallDict, smallDictSize);
-    /* Partial decompression wtih large prefix. */
+    /* Partial decompression with large prefix. */
     LZ4_decompress_safe_partial_usingDict((char const*)dataAfterDict, dst, size,
                                   dstCapacity, dstCapacity, largeDict, largeDictSize);
     free(dst);
diff --git a/ossfuzz/fuzz_helpers.h b/ossfuzz/fuzz_helpers.h
index efd9acf..4ef1c98 100644
--- a/ossfuzz/fuzz_helpers.h
+++ b/ossfuzz/fuzz_helpers.h
@@ -44,7 +44,7 @@
           : (fprintf(stderr, "%s: %u: Assertion: `%s' failed. %s\n", __FILE__, \
                      __LINE__, FUZZ_QUOTE(cond), (msg)),                       \
              abort()))
-#define FUZZ_ASSERT(cond) FUZZ_ASSERT_MSG((cond), "");
+#define FUZZ_ASSERT(cond) FUZZ_ASSERT_MSG((cond), "")
 
 #if defined(__GNUC__)
 #define FUZZ_STATIC static __inline __attribute__((unused))
diff --git a/programs/.gitignore b/programs/.gitignore
index 9ffadd9..c89f52a 100644
--- a/programs/.gitignore
+++ b/programs/.gitignore
@@ -4,6 +4,7 @@
 lz4cat
 lz4c
 lz4c32
+lz4-nomt
 lz4-wlib
 datagen
 frametest
diff --git a/programs/Android.bp b/programs/Android.bp
index 89540d1..7820a1c 100644
--- a/programs/Android.bp
+++ b/programs/Android.bp
@@ -18,12 +18,17 @@
 cc_binary_host {
     name: "lz4",
     srcs: [
-        "datagen.c",
         "bench.c",
         "lz4io.c",
         "lz4cli.c",
+        "timefn.c",
+        "threadpool.c",
+        "lorem.c",
     ],
-    cflags: ["-Wall", "-Werror"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
     static_libs: ["liblz4"],
     stl: "libc++_static",
 }
@@ -36,10 +41,12 @@
         "-Werror",
     ],
     srcs: [
-        "datagen.c",
         "bench.c",
         "lz4io.c",
         "lz4cli.c",
+        "timefn.c",
+        "threadpool.c",
+        "lorem.c",
     ],
     static_libs: ["liblz4"],
     stl: "libc++_static",
diff --git a/programs/COPYING b/programs/COPYING
index d159169..c728282 100644
--- a/programs/COPYING
+++ b/programs/COPYING
@@ -1,339 +1,83 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
+Full name:
+GNU General Public License v2.0 or later
 
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+Short identifier:
+GPL-2.0-or-later
 
-                            Preamble
+Text:
+GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991
 
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
 
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
+Preamble
 
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
 
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
 
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
+To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
 
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
 
-  The precise terms and conditions for copying, distribution and
-modification follow.
+We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
 
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
 
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
+Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
 
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
+The precise terms and conditions for copying, distribution and modification follow.
 
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
+0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
 
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
+1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
 
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
+2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
+b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
+c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
 
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
 
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
+In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
 
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
+3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
+a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
 
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
+If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
 
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
+4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
 
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
+5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
 
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
+6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
 
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
+7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
 
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
 
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
 
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
+8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
 
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
+9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
 
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
+10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+NO WARRANTY
 
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
diff --git a/programs/Makefile b/programs/Makefile
index ace0d03..643ce14 100644
--- a/programs/Makefile
+++ b/programs/Makefile
@@ -1,6 +1,6 @@
 # ##########################################################################
 # LZ4 programs - Makefile
-# Copyright (C) Yann Collet 2011-2020
+# Copyright (C) Yann Collet 2011-2023
 #
 # This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets
 #
@@ -28,30 +28,30 @@
 # lz4c  : CLU, supporting also legacy lz4demo arguments
 # lz4c32: Same as lz4c, but forced to compile in 32-bits mode
 # ##########################################################################
-SED = sed
+SED ?= sed
 
 # Version numbers
-LZ4DIR   := ../lib
-LIBVER_SRC := $(LZ4DIR)/lz4.h
-LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
-LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
-LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
+LIBDIR   := ../lib
+LIBVER_SRC := $(LIBDIR)/lz4.h
+LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
+LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
+LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
 LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
 LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
 LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
 LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT))
 LIBVER   := $(shell echo $(LIBVER_SCRIPT))
 
-LIBFILES  = $(wildcard $(LZ4DIR)/*.c)
+LIBFILES  = $(wildcard $(LIBDIR)/*.c)
 SRCFILES  = $(sort $(LIBFILES) $(wildcard *.c))
 OBJFILES  = $(SRCFILES:.c=.o)
 
-CPPFLAGS += -I$(LZ4DIR) -DXXH_NAMESPACE=LZ4_
-CFLAGS   ?= -O3
 DEBUGFLAGS= -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
             -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
             -Wpointer-arith -Wstrict-aliasing=1
-CFLAGS   += $(DEBUGFLAGS) $(MOREFLAGS)
+USERCFLAGS:= -O3 $(CFLAGS) # -O3 can be overruled by user-provided -Ox level
+CFLAGS    = $(DEBUGFLAGS) $(USERCFLAGS)
+CPPFLAGS += -I$(LIBDIR) -DXXH_NAMESPACE=LZ4_
 
 include ../Makefile.inc
 
@@ -60,20 +60,37 @@
 LDFLAGS  += -lrt
 endif
 
-FLAGS     = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
+ALLFLAGS  = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
+
+# thread detection
+NUM_SYMBOL   := \#
+NO_THREAD_MSG:= ==> no multithread support: building for single-thread mode only
+HAVE_PTHREAD := $(shell printf '$(NUM_SYMBOL)include <pthread.h>\nint main(void) { return 0; }' > have_pthread.c && $(CC) $(ALLFLAGS) -o have_pthread$(EXT) have_pthread.c -pthread 2> $(VOID) && rm -f have_pthread$(EXT) && echo 1 || echo 0; rm have_pthread.c)
+HAVE_MULTITHREAD  := $(shell [ "$(HAVE_PTHREAD)" -eq "1" -o -n "$(filter Windows%,$(OS))" ] && echo 1 || echo 0)
+ifeq ($(HAVE_MULTITHREAD), 1)
+  THREAD_MSG := ==> building with multithreading support
+  THREAD_CPP := -DLZ4IO_MULTITHREAD
+  ifeq ($(HAVE_PTHREAD), 1)
+    THREAD_LD  := -pthread
+  endif
+else
+  THREAD_MSG := $(NO_THREAD_MSG)
+endif
 
 LZ4_VERSION=$(LIBVER)
-MD2ROFF   = ronn
+MD2ROFF    = ronn
 MD2ROFF_FLAGS = --roff --warnings --manual="User Commands" --organization="lz4 $(LZ4_VERSION)"
 
-
+.PHONY:default
 default: lz4-release
 
 # silent mode by default; verbose can be triggered by V=1 or VERBOSE=1
 $(V)$(VERBOSE).SILENT:
 
-all: lz4 lz4c
+.PHONY:all
+all: lz4 lz4-nomt lz4c unlz4 lz4cat
 
+.PHONY:all32
 all32: CFLAGS+=-m32
 all32: all
 
@@ -81,64 +98,89 @@
 lz4-exe.rc: lz4-exe.rc.in
 	@echo creating executable resource
 	$(SED) -e 's|@PROGNAME@|lz4|' \
-         -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
-         -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
-         -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
-         -e 's|@EXT@|$(EXT)|g' \
-          $< >$@
+           -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
+           -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
+           -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
+           -e 's|@EXT@|.exe|g' \
+           $< >$@
 
 lz4-exe.o: lz4-exe.rc
 	$(WINDRES) -i lz4-exe.rc -o lz4-exe.o
 
+lz4: CPPFLAGS += $(THREAD_CPP)
+lz4: LDFLAGS += $(THREAD_LD)
 lz4: $(OBJFILES) lz4-exe.o
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	echo "$(THREAD_MSG)"
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 else
+lz4: CPPFLAGS += $(THREAD_CPP)
+lz4: LDFLAGS += $(THREAD_LD)
 lz4: $(OBJFILES)
-	$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
+	echo "$(THREAD_MSG)"
+	$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
 endif
+CLEAN += lz4
 
 .PHONY: lz4-release
 lz4-release: DEBUGFLAGS=
+lz4-release: CPPFLAGS+=-DNDEBUG
 lz4-release: lz4
 
+CLEAN += lz4-nomt
+lz4-nomt: $(SRCFILES)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
+
+CLEAN += lz4-wlib
 lz4-wlib: LIBFILES =
-lz4-wlib: SRCFILES+= $(LZ4DIR)/xxhash.c  # benchmark unit needs XXH64()
-lz4-wlib: LDFLAGS += -L $(LZ4DIR)
+lz4-wlib: SRCFILES+= $(LIBDIR)/xxhash.c  # benchmark unit needs XXH64()
+lz4-wlib: LDFLAGS += -L $(LIBDIR)
 lz4-wlib: LDLIBS   = -llz4
 lz4-wlib: liblz4 $(OBJFILES)
 	@echo WARNING: $@ must link to an extended variant of the dynamic library which also exposes unstable symbols
-	$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
+	$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
 
 .PHONY:liblz4
 liblz4:
-	CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LZ4DIR) liblz4
+	CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LIBDIR) liblz4
 
+CLEAN += lz4c
 lz4c: lz4
 	$(LN_SF) lz4$(EXT) lz4c$(EXT)
 
+CLEAN += lz4c32
 lz4c32: CFLAGS += -m32
 lz4c32 : $(SRCFILES)
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
+
+CLEAN += unlz4
+unlz4: lz4
+	$(LN_SF) lz4$(EXT) unlz4$(EXT)
+
+CLEAN += lz4cat
+lz4cat: lz4
+	$(LN_SF) lz4$(EXT) lz4cat$(EXT)
 
 lz4.1: lz4.1.md $(LIBVER_SRC)
 	cat $< | $(MD2ROFF) $(MD2ROFF_FLAGS) | $(SED) -n '/^\.\\\".*/!p' > $@
 
+.PHONY:man
 man: lz4.1
 
+.PHONY:clean-man
 clean-man:
 	$(RM) lz4.1
 
+.PHONY:preview-man
 preview-man: clean-man man
 	man ./lz4.1
 
+.PHONY:clean
 clean:
 ifeq ($(WINBASED),yes)
 	$(RM) *.rc
 endif
-	$(MAKE) -C $(LZ4DIR) $@ > $(VOID)
-	$(RM) core *.o *.test tmp* \
-           lz4$(EXT) lz4c$(EXT) lz4c32$(EXT) lz4-wlib$(EXT) \
-           unlz4$(EXT) lz4cat$(EXT)
+	$(MAKE) -C $(LIBDIR) $@ > $(VOID)
+	$(RM) $(CLEAN) *.o tmp* *.test core
 	@echo Cleaning completed
 
 
@@ -147,12 +189,6 @@
 #-----------------------------------------------------------------------------
 ifeq ($(POSIX_ENV),Yes)
 
-unlz4: lz4
-	$(LN_SF) lz4$(EXT) unlz4$(EXT)
-
-lz4cat: lz4
-	$(LN_SF) lz4$(EXT) lz4cat$(EXT)
-
 DESTDIR     ?=
 # directory variables : GNU conventions prefer lowercase
 # see https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html
@@ -170,9 +206,10 @@
 MAN1DIR     ?= $(mandir)/man1
 man1dir     ?= $(MAN1DIR)
 
+.PHONY: install
 install: lz4
 	@echo Installing binaries in $(DESTDIR)$(bindir)
-	$(INSTALL_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
+	$(MAKE_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
 	$(INSTALL_PROGRAM) lz4$(EXT) $(DESTDIR)$(bindir)/lz4$(EXT)
 	$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4c$(EXT)
 	$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4cat$(EXT)
@@ -184,6 +221,7 @@
 	$(LN_SF) lz4.1 $(DESTDIR)$(man1dir)/unlz4.1
 	@echo lz4 installation completed
 
+.PHONY: uninstall
 uninstall:
 	$(RM) $(DESTDIR)$(bindir)/lz4cat$(EXT)
 	$(RM) $(DESTDIR)$(bindir)/unlz4$(EXT)
diff --git a/programs/README.md b/programs/README.md
index c1995af..104e31a 100644
--- a/programs/README.md
+++ b/programs/README.md
@@ -2,38 +2,68 @@
 ============================================
 
 ### Build
-The Command Line Interface (CLI) can be generated
-using the `make` command without any additional parameters.
-
-The `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
-including standard targets (`all`, `install`, `clean`, etc.)
-and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
-
-For advanced use cases, there are targets to different variations of the CLI:
-- `lz4` : default CLI, with a command line syntax close to gzip
-- `lz4c` : Same as `lz4` with additional support legacy lz4 commands (incompatible with gzip)
-- `lz4c32` : Same as `lz4c`, but forced to compile in 32-bits mode
+The `lz4` Command Line Interface (CLI) is generated
+using the `make` command, no additional parameter required.
 
 The CLI generates and decodes [LZ4-compressed frames](../doc/lz4_Frame_format.md).
 
+For more control over the build process,
+the `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
+including standard targets (`all`, `install`, `clean`, etc.)
+and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
 
-#### Aggregation of parameters
-CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined into `-b1e18i1`.
+The makefile offer several targets for various use cases:
+- `lz4` : default CLI, with a command line syntax similar to gzip
+- `lz4c` : supports legacy lz4 commands (incompatible with gzip)
+- `lz4c32` : Same as `lz4c`, but generates a 32-bits executable
+- `unlz4`, `lz4cat` : symlinks to `lz4`, default to decompression and `cat` compressed files
+- `man` : generates the man page, from `lz4.1.md` markdown source
+
+#### Makefile Build variables
+- `HAVE_MULTITHREAD` : build with multithreading support. Detection is generally automatic, but can be forced to `0` or `1` if needed. This is for example useful when cross-compiling for Windows from Linux.
+- `HAVE_PTHREAD` : determines presence of `<pthread>` support. Detection is automatic, but can be forced to `0` or `1` if needed. This is in turn used by `make` to automatically trigger multithreading support.
+
+#### C Preprocessor Build variables
+These variables are read by the preprocessor at compilation time. They influence executable behavior, such as default starting values, and are exposed from `programs/lz4conf.h`. These variables can manipulated by any build system.
+Assignment methods vary depending on environments.
+On a typical `posix` + `gcc` + `make` setup, they can be defined with `CPPFLAGS=-DVARIABLE=value` assignment.
+- `LZ4_CLEVEL_DEFAULT`: default compression level when none provided. Default is `1`.
+- `LZ4IO_MULTITHREAD`: enable multithreading support. Default is disabled.
+- `LZ4_NBWORKERS_DEFAULT`: default nb of worker threads used in multithreading mode (can be overridden with command `-T#`).
+   Default is `0`, which means "auto-determine" based on local cpu.
+- `LZ4_NBWORKERS_MAX`: absolute maximum nb of workers that can be requested at runtime.
+   Currently set to 200 by default.
+   This is mostly meant to protect the system against unreasonable and likely bogus requests, such as a million threads.
+- `LZ4_BLOCKSIZEID_DEFAULT`: default `lz4` block size code. Valid values are [4-7], corresponding to 64 KB, 256 KB, 1 MB and 4 MB. At the time of this writing, default is 7, corresponding to 4 MB block size.
+
+#### Environment Variables
+It's possible to pass some parameters to `lz4` via environment variables.
+This can be useful in situations where `lz4` is known to be invoked (from within a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
+The environment variable has higher priority than binary default, but lower priority than corresponding runtime command.
+When set as global environment variables, it can enforce personalized defaults different from the binary set ones.
+
+`LZ4_CLEVEL` can be used to specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
+
+`LZ4_NBWORKERS` can be used to specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
+
+### Aggregation of parameters
+The `lz4` CLI supports aggregation for short commands. For example, `-d`, `-q`, and `-f` can be joined into `-dqf`.
+Aggregation doesn't work for `--long-commands`, which **must** be separated.
 
 
-#### Benchmark in Command Line Interface
-CLI includes in-memory compression benchmark module for lz4.
-The benchmark is conducted using a given filename.
-The file is read into memory.
-It makes benchmark more precise as it eliminates I/O overhead.
+### Benchmark in Command Line Interface
+`lz4` CLI includes an in-memory compression benchmark module, triggered by command `-b#`, with `#` representing the compression level.
+The benchmark is conducted on a provided list of filenames.
+The files are then read entirely into memory, to eliminate I/O overhead.
+When multiple files are provided, they are bundled into the same benchmark session (though each file is a separate compression / decompression). Using `-S` command separates them (one session per file).
+When no file is provided, uses an internal Lorem Ipsum generator instead.
 
 The benchmark measures ratio, compressed size, compression and decompression speed.
-One can select compression levels starting from `-b` and ending with `-e`.
-The `-i` parameter selects a number of seconds used for each of tested levels.
+One can select multiple compression levels starting from `-b` and ending with `-e` (ascending).
+The `-i` parameter selects a number of seconds used for each session.
 
 
-
-#### Usage of Command Line Interface
+### Usage of Command Line Interface
 The full list of commands can be obtained with `-h` or `-H` parameter:
 ```
 Usage :
diff --git a/programs/bench.c b/programs/bench.c
index 4d35ef9..64e28ca 100644
--- a/programs/bench.c
+++ b/programs/bench.c
@@ -43,9 +43,10 @@
 #include <time.h>        /* clock_t, clock, CLOCKS_PER_SEC */
 #include <assert.h>      /* assert */
 
-#include "datagen.h"     /* RDG_genBuffer */
+#include "lorem.h"       /* LOREM_genBuffer */
 #include "xxhash.h"
 #include "bench.h"
+#include "timefn.h"
 
 #define LZ4_STATIC_LINKING_ONLY
 #include "lz4.h"
@@ -66,7 +67,7 @@
 #define NBSECONDS             3
 #define TIMELOOP_MICROSEC     1*1000000ULL /* 1 second */
 #define TIMELOOP_NANOSEC      1*1000000000ULL /* 1 second */
-#define ACTIVEPERIOD_MICROSEC 70*1000000ULL /* 70 seconds */
+#define ACTIVEPERIOD_NANOSEC 70*1000000000ULL /* 70 seconds */
 #define COOLPERIOD_SEC        10
 #define DECOMP_MULT           1 /* test decompression DECOMP_MULT times longer than compression */
 
@@ -78,14 +79,14 @@
 
 static const size_t maxMemory = (sizeof(size_t)==4)  ?  (2 GB - 64 MB) : (size_t)(1ULL << ((sizeof(size_t)*8)-31));
 
-static U32 g_compressibilityDefault = 50;
-
 
 /* *************************************
 *  console display
 ***************************************/
+#define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
+#define OUTLEVEL(l, ...)     if (g_displayLevel>=(l)) { DISPLAYOUT(__VA_ARGS__); }
 #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=(l)) { DISPLAY(__VA_ARGS__); }
 static U32 g_displayLevel = 2;   /* 0 : no display;   1: errors;   2 : + result + interaction + warnings;   3 : + progression;   4 : + information */
 
 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
@@ -103,14 +104,14 @@
 #  define DEBUG 0
 #endif
 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
-#define END_PROCESS(error, ...)                                             \
-{                                                                         \
+#define END_PROCESS(error, ...)                                           \
+do {                                                                      \
     DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
     DISPLAYLEVEL(1, "Error %i : ", error);                                \
     DISPLAYLEVEL(1, __VA_ARGS__);                                         \
     DISPLAYLEVEL(1, "\n");                                                \
     exit(error);                                                          \
-}
+} while (0)
 
 #define LZ4_isError(errcode) (errcode==0)
 
@@ -186,7 +187,7 @@
     pThis->LZ4_dictStream = LZ4_createStream();
     pThis->LZ4_streamHC = NULL;
     pThis->LZ4_dictStreamHC = NULL;
-    LZ4_loadDict(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
+    LZ4_loadDictSlow(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
 }
 
 static void
@@ -196,81 +197,84 @@
     pThis->LZ4_dictStream = NULL;
     pThis->LZ4_streamHC = LZ4_createStreamHC();
     pThis->LZ4_dictStreamHC = LZ4_createStreamHC();
+    LZ4_resetStreamHC_fast(pThis->LZ4_dictStreamHC, pThis->cLevel);
     LZ4_loadDictHC(pThis->LZ4_dictStreamHC, pThis->dictBuf, pThis->dictSize);
 }
 
 static void
-LZ4_compressResetNoStream(const struct compressionParameters* pThis)
+LZ4_compressResetNoStream(const struct compressionParameters* cparams)
 {
-    (void)pThis;
+    (void)cparams;
 }
 
 static void
-LZ4_compressResetStream(const struct compressionParameters* pThis)
+LZ4_compressResetStream(const struct compressionParameters* cparams)
 {
-    LZ4_resetStream_fast(pThis->LZ4_stream);
-    LZ4_attach_dictionary(pThis->LZ4_stream, pThis->LZ4_dictStream);
+    LZ4_resetStream_fast(cparams->LZ4_stream);
+    LZ4_attach_dictionary(cparams->LZ4_stream, cparams->LZ4_dictStream);
 }
 
 static void
-LZ4_compressResetStreamHC(const struct compressionParameters* pThis)
+LZ4_compressResetStreamHC(const struct compressionParameters* cparams)
 {
-    LZ4_resetStreamHC_fast(pThis->LZ4_streamHC, pThis->cLevel);
-    LZ4_attach_HC_dictionary(pThis->LZ4_streamHC, pThis->LZ4_dictStreamHC);
+    LZ4_resetStreamHC_fast(cparams->LZ4_streamHC, cparams->cLevel);
+    LZ4_attach_HC_dictionary(cparams->LZ4_streamHC, cparams->LZ4_dictStreamHC);
 }
 
 static int
-LZ4_compressBlockNoStream(const struct compressionParameters* pThis,
+LZ4_compressBlockNoStream(const struct compressionParameters* cparams,
                           const char* src, char* dst,
                           int srcSize, int dstSize)
 {
-    int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
+    int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
     return LZ4_compress_fast(src, dst, srcSize, dstSize, acceleration);
 }
 
 static int
-LZ4_compressBlockNoStreamHC(const struct compressionParameters* pThis,
+LZ4_compressBlockNoStreamHC(const struct compressionParameters* cparams,
                             const char* src, char* dst,
                             int srcSize, int dstSize)
 {
-    return LZ4_compress_HC(src, dst, srcSize, dstSize, pThis->cLevel);
+    return LZ4_compress_HC(src, dst, srcSize, dstSize, cparams->cLevel);
 }
 
 static int
-LZ4_compressBlockStream(const struct compressionParameters* pThis,
+LZ4_compressBlockStream(const struct compressionParameters* cparams,
                         const char* src, char* dst,
                         int srcSize, int dstSize)
 {
-    int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
-    return LZ4_compress_fast_continue(pThis->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
+    int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
+    LZ4_compressResetStream(cparams);
+    return LZ4_compress_fast_continue(cparams->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
 }
 
 static int
-LZ4_compressBlockStreamHC(const struct compressionParameters* pThis,
+LZ4_compressBlockStreamHC(const struct compressionParameters* cparams,
                           const char* src, char* dst,
                           int srcSize, int dstSize)
 {
-    return LZ4_compress_HC_continue(pThis->LZ4_streamHC, src, dst, srcSize, dstSize);
+    LZ4_compressResetStreamHC(cparams);
+    return LZ4_compress_HC_continue(cparams->LZ4_streamHC, src, dst, srcSize, dstSize);
 }
 
 static void
-LZ4_compressCleanupNoStream(const struct compressionParameters* pThis)
+LZ4_compressCleanupNoStream(const struct compressionParameters* cparams)
 {
-    (void)pThis;
+    (void)cparams;
 }
 
 static void
-LZ4_compressCleanupStream(const struct compressionParameters* pThis)
+LZ4_compressCleanupStream(const struct compressionParameters* cparams)
 {
-    LZ4_freeStream(pThis->LZ4_stream);
-    LZ4_freeStream(pThis->LZ4_dictStream);
+    LZ4_freeStream(cparams->LZ4_stream);
+    LZ4_freeStream(cparams->LZ4_dictStream);
 }
 
 static void
-LZ4_compressCleanupStreamHC(const struct compressionParameters* pThis)
+LZ4_compressCleanupStreamHC(const struct compressionParameters* cparams)
 {
-    LZ4_freeStreamHC(pThis->LZ4_streamHC);
-    LZ4_freeStreamHC(pThis->LZ4_dictStreamHC);
+    LZ4_freeStreamHC(cparams->LZ4_streamHC);
+    LZ4_freeStreamHC(cparams->LZ4_dictStreamHC);
 }
 
 static void
@@ -367,6 +371,7 @@
     size_t const maxInSize = (size_t)LZ4_MAX_INPUT_SIZE / decMultiplier;
     size_t const maxDecSize = srcSize < maxInSize ? srcSize * decMultiplier : LZ4_MAX_INPUT_SIZE;
     void* const resultBuffer = malloc(maxDecSize);
+    int benchError = 0;
     U32 nbBlocks;
     struct compressionParameters compP;
 
@@ -410,7 +415,7 @@
     }   }   }
 
     /* warming up memory */
-    RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1);
+    memset(compressedBuffer, ' ', maxCompressedSize);
 
     /* decode-only mode : copy input to @compressedBuffer */
     if (g_decodeOnly) {
@@ -423,11 +428,11 @@
     /* Bench */
     {   U64 fastestC = (U64)(-1LL), fastestD = (U64)(-1LL);
         U64 const crcOrig = XXH64(srcBuffer, srcSize, 0);
-        UTIL_time_t coolTime = UTIL_getTime();
+        TIME_t coolTime = TIME_getTime();
         U64 const maxTime = (g_nbSeconds * TIMELOOP_NANOSEC) + 100;
         U32 nbCompressionLoops = (U32)((5 MB) / (srcSize+1)) + 1;  /* conservative initial compression speed estimate */
         U32 nbDecodeLoops = (U32)((200 MB) / (srcSize+1)) + 1;  /* conservative initial decode speed estimate */
-        U64 totalCTime=0, totalDTime=0;
+        Duration_ns totalCTime=0, totalDTime=0;
         U32 cCompleted=(g_decodeOnly==1), dCompleted=0;
 #       define NB_MARKS 4
         const char* const marks[NB_MARKS] = { " |", " /", " =",  "\\" };
@@ -437,23 +442,27 @@
         double ratio = 0.;
 
         DISPLAYLEVEL(2, "\r%79s\r", "");
+        if (g_nbSeconds==0) { nbCompressionLoops = 1; nbDecodeLoops = 1; }
         while (!cCompleted || !dCompleted) {
             /* overheat protection */
-            if (UTIL_clockSpanMicro(coolTime) > ACTIVEPERIOD_MICROSEC) {
+            if (TIME_clockSpan_ns(coolTime) > ACTIVEPERIOD_NANOSEC) {
                 DISPLAYLEVEL(2, "\rcooling down ...    \r");
                 UTIL_sleep(COOLPERIOD_SEC);
-                coolTime = UTIL_getTime();
+                coolTime = TIME_getTime();
             }
 
             /* Compression */
             DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->\r", marks[markNb], displayName, (U32)totalRSize);
-            if (!cCompleted) memset(compressedBuffer, 0xE5, maxCompressedSize);  /* warm up and erase compressed buffer */
+            if (!cCompleted) {
+                memset(compressedBuffer, 0xE5, maxCompressedSize);  /* warm up and erase compressed buffer */
+                { U32 blockNb; for (blockNb=0; blockNb<nbBlocks; blockNb++) blockTable[blockNb].cSize = 0; }
+            }
 
             UTIL_sleepMilli(1);  /* give processor time to other processes */
-            UTIL_waitForNextTick();
+            TIME_waitForNextTick();
 
             if (!cCompleted) {   /* still some time to do compression tests */
-                UTIL_time_t const clockStart = UTIL_getTime();
+                TIME_t const timeStart = TIME_getTime();
                 U32 nbLoops;
                 for (nbLoops=0; nbLoops < nbCompressionLoops; nbLoops++) {
                     U32 blockNb;
@@ -463,20 +472,23 @@
                             &compP,
                             blockTable[blockNb].srcPtr, blockTable[blockNb].cPtr,
                             (int)blockTable[blockNb].srcSize, (int)blockTable[blockNb].cRoom);
-                        if (LZ4_isError(rSize)) END_PROCESS(1, "LZ4 compression failed");
+                        if (LZ4_isError(rSize)) {
+                            DISPLAY("LZ4 compression failed on block %u \n", blockNb);
+                            benchError =1 ;
+                        }
                         blockTable[blockNb].cSize = rSize;
                 }   }
-                {   U64 const clockSpan = UTIL_clockSpanNano(clockStart);
-                    if (clockSpan > 0) {
-                        if (clockSpan < fastestC * nbCompressionLoops)
-                            fastestC = clockSpan / nbCompressionLoops;
+                {   Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
+                    if (duration_ns > 0) {
+                        if (duration_ns < fastestC * nbCompressionLoops)
+                            fastestC = duration_ns / nbCompressionLoops;
                         assert(fastestC > 0);
                         nbCompressionLoops = (U32)(TIMELOOP_NANOSEC / fastestC) + 1;  /* aim for ~1sec */
                     } else {
                         assert(nbCompressionLoops < 40000000);   /* avoid overflow */
                         nbCompressionLoops *= 100;
                     }
-                    totalCTime += clockSpan;
+                    totalCTime += duration_ns;
                     cCompleted = totalCTime>maxTime;
                 }
 
@@ -485,10 +497,11 @@
                 cSize += !cSize;  /* avoid div by 0 */
                 ratio = (double)totalRSize / (double)cSize;
                 markNb = (markNb+1) % NB_MARKS;
-                DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
+                OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
                         marks[markNb], displayName,
                         (U32)totalRSize, (U32)cSize, ratio,
-                        ((double)totalRSize / fastestC) * 1000 );
+                        ((double)totalRSize / (double)fastestC) * 1000 );
+                fflush(NULL);
             }
             (void)fastestD; (void)crcOrig;   /*  unused when decompression disabled */
 #if 1
@@ -496,14 +509,14 @@
             if (!dCompleted) memset(resultBuffer, 0xD6, srcSize);  /* warm result buffer */
 
             UTIL_sleepMilli(5); /* give processor time to other processes */
-            UTIL_waitForNextTick();
+            TIME_waitForNextTick();
 
             if (!dCompleted) {
                 const DecFunction_f decFunction = g_decodeOnly ?
                     LZ4F_decompress_binding : LZ4_decompress_safe_usingDict;
                 const char* const decString = g_decodeOnly ?
                     "LZ4F_decompress" : "LZ4_decompress_safe_usingDict";
-                UTIL_time_t const clockStart = UTIL_getTime();
+                TIME_t const timeStart = TIME_getTime();
                 U32 nbLoops;
 
                 for (nbLoops=0; nbLoops < nbDecodeLoops; nbLoops++) {
@@ -522,22 +535,22 @@
                                 decString, blockNb, (unsigned)blockTable[blockNb].srcSize);
                             if (g_decodeOnly)
                                 DISPLAY("Is input using LZ4 Frame format ? \n");
-                            END_PROCESS(2, "error during decoding");
+                            benchError = 1;
                             break;
                         }
                         blockTable[blockNb].resSize = (size_t)regenSize;
                 }   }
-                {   U64 const clockSpan = UTIL_clockSpanNano(clockStart);
-                    if (clockSpan > 0) {
-                        if (clockSpan < fastestD * nbDecodeLoops)
-                            fastestD = clockSpan / nbDecodeLoops;
+                {   Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
+                    if (duration_ns > 0) {
+                        if (duration_ns < fastestD * nbDecodeLoops)
+                            fastestD = duration_ns / nbDecodeLoops;
                         assert(fastestD > 0);
                         nbDecodeLoops = (U32)(TIMELOOP_NANOSEC / fastestD) + 1;  /* aim for ~1sec */
                     } else {
                         assert(nbDecodeLoops < 40000000);   /* avoid overflow */
                         nbDecodeLoops *= 100;
                     }
-                    totalDTime += clockSpan;
+                    totalDTime += duration_ns;
                     dCompleted = totalDTime > (DECOMP_MULT*maxTime);
             }   }
 
@@ -548,11 +561,12 @@
             }
             markNb = (markNb+1) % NB_MARKS;
             ratio  = (double)totalRSize / (double)cSize;
-            DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s ,%6.1f MB/s\r",
+            OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s, %6.1f MB/s\r",
                     marks[markNb], displayName,
                     (U32)totalRSize, (U32)cSize, ratio,
-                    ((double)totalRSize / fastestC) * 1000,
-                    ((double)totalRSize / fastestD) * 1000);
+                    ((double)totalRSize / (double)fastestC) * 1000,
+                    ((double)totalRSize / (double)fastestD) * 1000);
+            fflush(NULL);
 
             /* CRC Checking (not possible in decode-only mode)*/
             if (!g_decodeOnly) {
@@ -560,6 +574,7 @@
                 if (crcOrig!=crcCheck) {
                     size_t u;
                     DISPLAY("\n!!! WARNING !!! %17s : Invalid Checksum : %x != %x   \n", displayName, (unsigned)crcOrig, (unsigned)crcCheck);
+                    benchError = 1;
                     for (u=0; u<srcSize; u++) {
                         if (((const BYTE*)srcBuffer)[u] != ((const BYTE*)resultBuffer)[u]) {
                             U32 segNb, bNb, pos;
@@ -582,15 +597,17 @@
 #endif
         }   /* for (testNb = 1; testNb <= (g_nbSeconds + !g_nbSeconds); testNb++) */
 
+        OUTLEVEL(2, "%2i#\n", cLevel);
+
+        /* quiet mode */
         if (g_displayLevel == 1) {
-            double const cSpeed = ((double)srcSize / fastestC) * 1000;
-            double const dSpeed = ((double)srcSize / fastestD) * 1000;
+            double const cSpeed = ((double)srcSize / (double)fastestC) * 1000;
+            double const dSpeed = ((double)srcSize / (double)fastestD) * 1000;
+            DISPLAYOUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s ", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
             if (g_additionalParam)
-                DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, g_additionalParam);
-            else
-                DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
+                DISPLAYOUT("(param=%d)", g_additionalParam);
+            DISPLAYOUT("\n");
         }
-        DISPLAYLEVEL(2, "%2i#\n", cLevel);
     }   /* Bench */
 
     /* clean up */
@@ -598,7 +615,7 @@
     free(blockTable);
     free(compressedBuffer);
     free(resultBuffer);
-    return 0;
+    return benchError;
 }
 
 
@@ -626,13 +643,13 @@
 }
 
 
-static void BMK_benchCLevel(void* srcBuffer, size_t benchedSize,
+static int BMK_benchCLevel(void* srcBuffer, size_t benchedSize,
                             const char* displayName, int cLevel, int cLevelLast,
                             const size_t* fileSizes, unsigned nbFiles,
                             const char* dictBuf, int dictSize)
 {
     int l;
-
+    int benchError = 0;
     const char* pch = strrchr(displayName, '\\'); /* Windows */
     if (!pch) pch = strrchr(displayName, '/'); /* Linux */
     if (pch) displayName = pch+1;
@@ -645,11 +662,13 @@
     if (cLevelLast < cLevel) cLevelLast = cLevel;
 
     for (l=cLevel; l <= cLevelLast; l++) {
-        BMK_benchMem(srcBuffer, benchedSize,
-                     displayName, l,
-                     fileSizes, nbFiles,
-                     dictBuf, dictSize);
+        benchError |= BMK_benchMem(
+                            srcBuffer, benchedSize,
+                            displayName, l,
+                            fileSizes, nbFiles,
+                            dictBuf, dictSize);
     }
+    return benchError;
 }
 
 
@@ -688,12 +707,13 @@
     if (totalSize == 0) END_PROCESS(12, "no data to bench");
 }
 
-static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
-                               int cLevel, int cLevelLast,
-                               const char* dictBuf, int dictSize)
+static int BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
+                              int cLevel, int cLevelLast,
+                              const char* dictBuf, int dictSize)
 {
     void* srcBuffer;
     size_t benchedSize;
+    int benchError = 0;
     size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
     U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles);
     char mfName[20] = {0};
@@ -720,7 +740,7 @@
     /* Bench */
     snprintf (mfName, sizeof(mfName), " %u files", nbFiles);
     {   const char* displayName = (nbFiles > 1) ? mfName : fileNamesTable[0];
-        BMK_benchCLevel(srcBuffer, benchedSize,
+        benchError = BMK_benchCLevel(srcBuffer, benchedSize,
                         displayName, cLevel, cLevelLast,
                         fileSizes, nbFiles,
                         dictBuf, dictSize);
@@ -729,28 +749,35 @@
     /* clean up */
     free(srcBuffer);
     free(fileSizes);
+    return benchError;
 }
 
 
-static void BMK_syntheticTest(int cLevel, int cLevelLast, double compressibility,
-                              const char* dictBuf, int dictSize)
+static int BMK_syntheticTest(int cLevel, int cLevelLast,
+                             const char* dictBuf, int dictSize)
 {
-    char name[20] = {0};
-    size_t benchedSize = 10000000;
+    int benchError = 0;
+    size_t const benchedSize = 10000000;
     void* const srcBuffer = malloc(benchedSize);
 
     /* Memory allocation */
     if (!srcBuffer) END_PROCESS(21, "not enough memory");
 
     /* Fill input buffer */
-    RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
+    LOREM_genBuffer(srcBuffer, benchedSize, 0);
 
     /* Bench */
-    snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));
-    BMK_benchCLevel(srcBuffer, benchedSize, name, cLevel, cLevelLast, &benchedSize, 1, dictBuf, dictSize);
+    benchError = BMK_benchCLevel(srcBuffer, benchedSize,
+                    "Lorem ipsum",
+                    cLevel, cLevelLast,
+                    &benchedSize,
+                    1,
+                    dictBuf, dictSize);
 
     /* clean up */
     free(srcBuffer);
+
+    return benchError;
 }
 
 
@@ -759,15 +786,16 @@
                    int cLevel, int cLevelLast,
                    const char* dictBuf, int dictSize)
 {
+    int benchError = 0;
     unsigned fileNb;
     if (cLevel > LZ4HC_CLEVEL_MAX) cLevel = LZ4HC_CLEVEL_MAX;
     if (cLevelLast > LZ4HC_CLEVEL_MAX) cLevelLast = LZ4HC_CLEVEL_MAX;
     if (cLevelLast < cLevel) cLevelLast = cLevel;
 
     for (fileNb=0; fileNb<nbFiles; fileNb++)
-        BMK_benchFileTable(fileNamesTable+fileNb, 1, cLevel, cLevelLast, dictBuf, dictSize);
+        benchError |= BMK_benchFileTable(fileNamesTable+fileNb, 1, cLevel, cLevelLast, dictBuf, dictSize);
 
-    return 0;
+    return benchError;
 }
 
 
@@ -775,7 +803,7 @@
                    int cLevel, int cLevelLast,
                    const char* dictFileName)
 {
-    double const compressibility = (double)g_compressibilityDefault / 100;
+    int benchError = 0;
     char* dictBuf = NULL;
     size_t dictSize = 0;
 
@@ -823,15 +851,15 @@
         fclose(dictFile);
     }
 
-    if (nbFiles == 0)
-        BMK_syntheticTest(cLevel, cLevelLast, compressibility, dictBuf, (int)dictSize);
-    else {
+    if (nbFiles == 0) {
+        benchError = BMK_syntheticTest(cLevel, cLevelLast, dictBuf, (int)dictSize);
+    } else {
         if (g_benchSeparately)
-            BMK_benchFilesSeparately(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
+            benchError = BMK_benchFilesSeparately(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
         else
-            BMK_benchFileTable(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
+            benchError = BMK_benchFileTable(fileNamesTable, nbFiles, cLevel, cLevelLast, dictBuf, (int)dictSize);
     }
 
     free(dictBuf);
-    return 0;
+    return benchError;
 }
diff --git a/programs/lorem.c b/programs/lorem.c
new file mode 100644
index 0000000..92e02b9
--- /dev/null
+++ b/programs/lorem.c
@@ -0,0 +1,366 @@
+/*
+    lorem.c - lorem ipsum generator
+    Copyright (C) Yann Collet 2024
+
+    GPL v2 License
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+    You can contact the author at :
+   - LZ4 source repository : https://github.com/lz4/lz4
+   - Public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/* Implementation notes:
+ *
+ * This is a very simple lorem ipsum generator
+ * which features a static list of words
+ * and print them one after another randomly
+ * with a fake sentence / paragraph structure.
+ *
+ * The goal is to generate a printable text
+ * that can be used to fake a text compression scenario.
+ * The resulting compression / ratio curve of the lorem ipsum generator
+ * is more satisfying than the previous statistical generator,
+ * which was initially designed for entropy compression,
+ * and lacks a regularity more representative of text.
+ *
+ * The compression ratio achievable on the generated lorem ipsum
+ * is still a bit too good, presumably because the dictionary is a bit too
+ * small. It would be possible to create some more complex scheme, notably by
+ * enlarging the dictionary with a word generator, and adding grammatical rules
+ * (composition) and syntax rules. But that's probably overkill for the intended
+ * goal.
+ */
+
+#include "lorem.h"
+#include <assert.h>
+#include <limits.h> /* INT_MAX */
+#include <stdlib.h> /* malloc, abort */
+#include <string.h> /* memcpy */
+
+/* Define the word pool
+ * Note: all words must have a len <= 16 */
+static const char* kWords[] = {
+    "lorem",        "ipsum",      "dolor",       "sit",          "amet",
+    "consectetur",  "adipiscing", "elit",        "sed",          "do",
+    "eiusmod",      "tempor",     "incididunt",  "ut",           "labore",
+    "et",           "dolore",     "magna",       "aliqua",       "dis",
+    "lectus",       "vestibulum", "mattis",      "ullamcorper",  "velit",
+    "commodo",      "a",          "lacus",       "arcu",         "magnis",
+    "parturient",   "montes",     "nascetur",    "ridiculus",    "mus",
+    "mauris",       "nulla",      "malesuada",   "pellentesque", "eget",
+    "gravida",      "in",         "dictum",      "non",          "erat",
+    "nam",          "voluptat",   "maecenas",    "blandit",      "aliquam",
+    "etiam",        "enim",       "lobortis",    "scelerisque",  "fermentum",
+    "dui",          "faucibus",   "ornare",      "at",           "elementum",
+    "eu",           "facilisis",  "odio",        "morbi",        "quis",
+    "eros",         "donec",      "ac",          "orci",         "purus",
+    "turpis",       "cursus",     "leo",         "vel",          "porta",
+    "consequat",    "interdum",   "varius",      "vulputate",    "aliquet",
+    "pharetra",     "nunc",       "auctor",      "urna",         "id",
+    "metus",        "viverra",    "nibh",        "cras",         "mi",
+    "unde",         "omnis",      "iste",        "natus",        "error",
+    "perspiciatis", "voluptatem", "accusantium", "doloremque",   "laudantium",
+    "totam",        "rem",        "aperiam",     "eaque",        "ipsa",
+    "quae",         "ab",         "illo",        "inventore",    "veritatis",
+    "quasi",        "architecto", "beatae",      "vitae",        "dicta",
+    "sunt",         "explicabo",  "nemo",        "ipsam",        "quia",
+    "voluptas",     "aspernatur", "aut",         "odit",         "fugit",
+    "consequuntur", "magni",      "dolores",     "eos",          "qui",
+    "ratione",      "sequi",      "nesciunt",    "neque",        "porro",
+    "quisquam",     "est",        "dolorem",     "adipisci",     "numquam",
+    "eius",         "modi",       "tempora",     "incidunt",     "magnam",
+    "quaerat",      "ad",         "minima",      "veniam",       "nostrum",
+    "ullam",        "corporis",   "suscipit",    "laboriosam",   "nisi",
+    "aliquid",      "ex",         "ea",          "commodi",      "consequatur",
+    "autem",        "eum",        "iure",        "voluptate",    "esse",
+    "quam",         "nihil",      "molestiae",   "illum",        "fugiat",
+    "quo",          "pariatur",   "vero",        "accusamus",    "iusto",
+    "dignissimos",  "ducimus",    "blanditiis",  "praesentium",  "voluptatum",
+    "deleniti",     "atque",      "corrupti",    "quos",         "quas",
+    "molestias",    "excepturi",  "sint",        "occaecati",    "cupiditate",
+    "provident",    "similique",  "culpa",       "officia",      "deserunt",
+    "mollitia",     "animi",      "laborum",     "dolorum",      "fuga",
+    "harum",        "quidem",     "rerum",       "facilis",      "expedita",
+    "distinctio",   "libero",     "tempore",     "cum",          "soluta",
+    "nobis",        "eligendi",   "optio",       "cumque",       "impedit",
+    "minus",        "quod",       "maxime",      "placeat",      "facere",
+    "possimus",     "assumenda",  "repellendus", "temporibus",   "quibusdam",
+    "officiis",     "debitis",    "saepe",       "eveniet",      "voluptates",
+    "repudiandae",  "recusandae", "itaque",      "earum",        "hic",
+    "tenetur",      "sapiente",   "delectus",    "reiciendis",   "cillum",
+    "maiores",      "alias",      "perferendis", "doloribus",    "asperiores",
+    "repellat",     "minim",      "nostrud",     "exercitation", "ullamco",
+    "laboris",      "aliquip",    "duis",        "aute",         "irure",
+};
+#define KNBWORDS (sizeof(kWords) / sizeof(kWords[0]))
+static const unsigned kNbWords = KNBWORDS;
+
+static const char* g_words[KNBWORDS] = { NULL };
+static unsigned g_wordLen[KNBWORDS] = {0};
+static char* g_wordBuffer = NULL;
+
+/* simple 1-dimension distribution, based on word's length, favors small words
+ */
+static const int kWeights[]      = { 0, 8, 6, 4, 3, 2 };
+static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
+
+#define DISTRIB_SIZE_MAX 650
+static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
+static unsigned g_distribCount         = 0;
+
+static void countFreqs(
+        const unsigned wordLen[],
+        size_t nbWords,
+        const int* weights,
+        unsigned long nbWeights)
+{
+    unsigned total = 0;
+    size_t w;
+    for (w = 0; w < nbWords; w++) {
+        size_t len = wordLen[w];
+        int lmax;
+        if (len >= nbWeights)
+            len = nbWeights - 1;
+        lmax = weights[len];
+        total += (unsigned)lmax;
+    }
+    g_distribCount = total;
+    assert(g_distribCount <= DISTRIB_SIZE_MAX);
+}
+
+static void init_word_len(
+        const char* words[],
+        size_t nbWords)
+{
+    size_t n;
+    assert(words != NULL);
+    for (n=0; n<nbWords; n++) {
+        assert(words[n] != NULL);
+        assert(strlen(words[n]) < 256);
+        g_wordLen[n] = (unsigned char)strlen(words[n]);
+    }
+
+}
+
+static size_t sumLen(const unsigned* sizes, size_t s)
+{
+    size_t total = 0;
+    size_t n;
+    assert(sizes != NULL);
+    for (n=0; n<s; n++) {
+        total += sizes[n];
+    }
+    return total;
+}
+
+static void init_word_buffer(void)
+{
+    size_t n;
+    size_t const bufSize = sumLen(g_wordLen, kNbWords) + 16;
+    char* ptr;
+    assert(g_wordBuffer == NULL);
+    g_wordBuffer = (char*)calloc(1, bufSize);
+    if (g_wordBuffer == NULL) abort();
+    ptr = g_wordBuffer;
+    for (n=0; n<kNbWords; n++) {
+        memcpy(ptr, kWords[n], g_wordLen[n]);
+        g_words[n] = ptr;
+        ptr += g_wordLen[n];
+    }
+}
+
+static void init_word_distrib(
+        const unsigned wordLen[],
+        size_t nbWords,
+        const int* weights,
+        unsigned long nbWeights)
+{
+    size_t w, d = 0;
+    countFreqs(wordLen, nbWords, weights, nbWeights);
+    for (w = 0; w < nbWords; w++) {
+        size_t len = wordLen[w];
+        int l, lmax;
+        if (len >= nbWeights)
+            len = nbWeights - 1;
+        lmax = weights[len];
+        for (l = 0; l < lmax; l++) {
+            g_distrib[d++] = (int)w;
+        }
+    }
+}
+
+/* Note: this unit only works when invoked sequentially.
+ * No concurrent access is allowed */
+static char* g_ptr         = NULL;
+static size_t g_nbChars    = 0;
+static size_t g_maxChars   = 10000000;
+static unsigned g_randRoot = 0;
+
+#define RDG_rotl32(x, r) ((x << r) | (x >> (32 - r)))
+static unsigned LOREM_rand(unsigned range)
+{
+    static const unsigned prime1 = 2654435761U;
+    static const unsigned prime2 = 2246822519U;
+    unsigned rand32              = g_randRoot;
+    rand32 *= prime1;
+    rand32 ^= prime2;
+    rand32     = RDG_rotl32(rand32, 13);
+    g_randRoot = rand32;
+    return (unsigned)(((unsigned long long)rand32 * range) >> 32);
+}
+
+static void writeLastCharacters(void)
+{
+    size_t lastChars = g_maxChars - g_nbChars;
+    assert(g_maxChars >= g_nbChars);
+    if (lastChars == 0)
+        return;
+    g_ptr[g_nbChars++] = '.';
+    if (lastChars > 2) {
+        memset(g_ptr + g_nbChars, ' ', lastChars - 2);
+    }
+    if (lastChars > 1) {
+        g_ptr[g_maxChars - 1] = '\n';
+    }
+    g_nbChars = g_maxChars;
+}
+
+static void generateLastWord(const char* word, size_t wordLen, int upCase)
+{
+    if (g_nbChars + wordLen + 2 > g_maxChars) {
+        writeLastCharacters();
+        return;
+    }
+    memcpy(g_ptr + g_nbChars, word, wordLen);
+    if (upCase) {
+        static const char toUp = 'A' - 'a';
+        g_ptr[g_nbChars]       = (char)(g_ptr[g_nbChars] + toUp);
+    }
+    g_nbChars += wordLen;
+    writeLastCharacters();
+}
+
+#define MAX(a,b)  ((a)<(b)?(b):(a))
+static void generateWord(const char* word, size_t wordLen, const char* separator, size_t sepLen, int upCase)
+{
+    size_t const wlen = MAX(16, wordLen + 2);
+    if (g_nbChars + wlen > g_maxChars) {
+        generateLastWord(word, wordLen, upCase);
+        return;
+    }
+    assert(wordLen <= 16);
+    memcpy(g_ptr + g_nbChars, word, 16);
+    if (upCase) {
+        static const char toUp = 'A' - 'a';
+        g_ptr[g_nbChars]       = (char)(g_ptr[g_nbChars] + toUp);
+    }
+    g_nbChars += wordLen;
+    assert(sepLen <= 2);
+    memcpy(g_ptr + g_nbChars, separator, 2);
+    g_nbChars += sepLen;
+}
+
+static int about(unsigned target)
+{
+    return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
+}
+
+/* Function to generate a random sentence */
+static void generateSentence(int nbWords)
+{
+    int commaPos       = about(9);
+    int comma2         = commaPos + about(7);
+    int qmark          = (LOREM_rand(11) == 7);
+    const char* endSep = qmark ? "? " : ". ";
+    int i;
+    for (i = 0; i < nbWords; i++) {
+        int const wordID       = g_distrib[LOREM_rand(g_distribCount)];
+        const char* sep        = " ";
+        size_t sepLen = 1;
+        if (i == commaPos)
+            sep = ", ", sepLen=2;
+        if (i == comma2)
+            sep = ", ", sepLen=2;
+        if (i == nbWords - 1)
+            sep = endSep, sepLen=2;
+        generateWord(g_words[wordID], g_wordLen[wordID], sep, sepLen, i == 0);
+    }
+}
+
+static void generateParagraph(int nbSentences)
+{
+    int i;
+    for (i = 0; i < nbSentences; i++) {
+        int wordsPerSentence = about(11);
+        generateSentence(wordsPerSentence);
+    }
+    if (g_nbChars < g_maxChars) {
+        g_ptr[g_nbChars++] = '\n';
+    }
+    if (g_nbChars < g_maxChars) {
+        g_ptr[g_nbChars++] = '\n';
+    }
+}
+
+/* It's "common" for lorem ipsum generators to start with the same first
+ * pre-defined sentence */
+static void generateFirstSentence(void)
+{
+    int i;
+    for (i = 0; i < 18; i++) {
+        const char* separator = " ";
+        size_t sepLen = 1;
+        if (i == 4)
+            separator = ", ", sepLen=2;
+        if (i == 7)
+            separator = ", ", sepLen=2;
+        generateWord(g_words[i], g_wordLen[i], separator, sepLen, i == 0);
+    }
+    generateWord(g_words[18], g_wordLen[18], ". ", 2, 0);
+}
+
+size_t
+LOREM_genBlock(void* buffer, size_t size, unsigned seed, int first, int fill)
+{
+    g_ptr = (char*)buffer;
+    assert(size < INT_MAX);
+    g_maxChars = size;
+    g_nbChars  = 0;
+    g_randRoot = seed;
+    if (g_distribCount == 0) {
+        init_word_len(kWords, kNbWords);
+        init_word_buffer();
+        init_word_distrib(g_wordLen, kNbWords, kWeights, kNbWeights);
+    }
+
+    if (first) {
+        generateFirstSentence();
+    }
+    while (g_nbChars < g_maxChars) {
+        int sentencePerParagraph = about(7);
+        generateParagraph(sentencePerParagraph);
+        if (!fill)
+            break; /* only generate one paragraph in not-fill mode */
+    }
+    g_ptr = NULL;
+    return g_nbChars;
+}
+
+void LOREM_genBuffer(void* buffer, size_t size, unsigned seed)
+{
+    LOREM_genBlock(buffer, size, seed, 1, 1);
+}
diff --git a/programs/lorem.h b/programs/lorem.h
new file mode 100644
index 0000000..4b7bf57
--- /dev/null
+++ b/programs/lorem.h
@@ -0,0 +1,46 @@
+/*
+    lorem.h - lorem ipsum generator
+    Copyright (C) Yann Collet 2024
+
+    GPL v2 License
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+    You can contact the author at :
+   - LZ4 source repository : https://github.com/lz4/lz4
+   - Public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+
+#include <stddef.h>   /* size_t */
+
+/*
+ * LOREM_genBuffer():
+ * Generate @size bytes of compressible data using lorem ipsum generator
+ * into provided @buffer.
+ */
+void LOREM_genBuffer(void* buffer, size_t size, unsigned seed);
+
+/*
+ * LOREM_genBlock():
+ * Similar to LOREM_genBuffer, with additional controls :
+ * - @first : generate the first sentence
+ * - @fill : fill the entire @buffer,
+ *           if ==0: generate one paragraph at most.
+ * @return : nb of bytes generated into @buffer.
+ */
+size_t LOREM_genBlock(void* buffer, size_t size,
+                      unsigned seed,
+                      int first, int fill);
diff --git a/programs/lz4.1 b/programs/lz4.1
index 7cb98d6..e9631e8 100644
--- a/programs/lz4.1
+++ b/programs/lz4.1
@@ -1,5 +1,5 @@
 .
-.TH "LZ4" "1" "August 2022" "lz4 v1.9.4" "User Commands"
+.TH "LZ4" "1" "July 2024" "lz4 1.10.0" "User Commands"
 .
 .SH "NAME"
 \fBlz4\fR \- lz4, unlz4, lz4cat \- Compress or decompress \.lz4 files
@@ -17,7 +17,7 @@
 When writing scripts that need to decompress files, it is recommended to always use the name \fBlz4\fR with appropriate arguments (\fBlz4 \-d\fR or \fBlz4 \-dc\fR) instead of the names \fBunlz4\fR and \fBlz4cat\fR\.
 .
 .SH "DESCRIPTION"
-\fBlz4\fR is an extremely fast lossless compression algorithm, based on \fBbyte\-aligned LZ77\fR family of compression scheme\. \fBlz4\fR offers compression speeds > 500 MB/s per core, linearly scalable with multi\-core CPUs\. It features an extremely fast decoder, offering speed in multiple GB/s per core, typically reaching RAM speed limit on multi\-core systems\. The native file format is the \fB\.lz4\fR format\.
+\fBlz4\fR is a CLI based on \fBliblz4\fR, an extremely fast implementation of lossless compression algorithm\. It provides a default compression speed of typically > 500 MB/s per core\. Speed can traded for higher compression ratio, by increasing the compression level parameter\. While decompression is single\-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound\. \fBlz4\fR native file format is the \fB\.lz4\fR format\.
 .
 .SS "Difference between lz4 and gzip"
 \fBlz4\fR supports a command line syntax similar \fIbut not identical\fR to \fBgzip(1)\fR\. Differences are :
@@ -58,7 +58,7 @@
 It\'s possible to opt\-in to erase source files on successful compression or decompression, using \fB\-\-rm\fR command\.
 .
 .IP "\(bu" 4
-Consequently, \fBlz4 \-m \-\-rm\fR behaves the same as \fBgzip\fR\.
+Consequently, \fBlz4 \-m \-\-rm\fR features a behavior closer to the \fBgzip\fR one\.
 .
 .IP "" 0
 .
@@ -107,7 +107,7 @@
 .
 .TP
 \fB\-\-list\fR
-List information about \.lz4 files\. note : current implementation is limited to single\-frame \.lz4 files\.
+List information about \.lz4 files\. For detailed information on files with multiple frames, use \fB\-v\fR\. \fB\-\-list\fR automatically triggers \fB\-m\fR modifier\.
 .
 .SS "Operation modifiers"
 .
@@ -124,6 +124,10 @@
 Set highest compression level\. Same as \-12\.
 .
 .TP
+\fB\-T#\fR, \fB\-\-threads=#\fR
+Use \fB#\fR threads for compression\. When \fB0\fR, or none provided: automatically determined from nb of detected cores\.
+.
+.TP
 \fB\-\-favor\-decSpeed\fR
 Generate compressed data optimized for decompression speed\. Compressed data will be larger as a consequence (typically by ~0\.5%), while decompression speed will be improved by 5\-20%, depending on use cases\. This option only works in combination with very high compression levels (>=10)\.
 .
@@ -242,6 +246,17 @@
 \fB\-i#\fR
 Minimum evaluation time in seconds [1\-9] (default : 3)
 .
+.SS "Environment Variables"
+It\'s possible to pass some parameters to \fBlz4\fR via environment variables\. This can be useful in situations where \fBlz4\fR is known to be invoked (from a script for example) but there is no way to pass \fBlz4\fR parameters to influence the compression session\. The environment variable has higher priority than executable default, but lower priority than corresponding runtime command\. When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones\.
+.
+.TP
+\fBLZ4_CLEVEL\fR
+specify a default compression level that \fBlz4\fR employs for compression when no other compression level is specified on command line\. Executable default is generally \fB1\fR\.
+.
+.TP
+\fBLZ4_NBWORKERS\fR
+specify a default number of threads that \fBlz4\fR will employ for compression\. Executable default is generally \fB0\fR, which means auto\-determined based on local cpu\. This functionality is only relevant when \fBlz4\fR is compiled with multithreading support\. The maximum number of workers is capped at \fBLZ4_NBWORKERS_MAX\fR (\fB200\fR by default)\.
+.
 .SH "BUGS"
 Report bugs at: https://github\.com/lz4/lz4/issues
 .
diff --git a/programs/lz4.1.md b/programs/lz4.1.md
index 06c06cf..553cabc 100644
--- a/programs/lz4.1.md
+++ b/programs/lz4.1.md
@@ -18,13 +18,11 @@
 DESCRIPTION
 -----------
 
-`lz4` is an extremely fast lossless compression algorithm,
-based on **byte-aligned LZ77** family of compression scheme.
-`lz4` offers compression speeds > 500 MB/s per core,
-linearly scalable with multi-core CPUs.
-It features an extremely fast decoder, offering speed in multiple GB/s per core,
-typically reaching RAM speed limit on multi-core systems.
-The native file format is the `.lz4` format.
+`lz4` is a CLI based on `liblz4`, an extremely fast implementation of lossless compression algorithm.
+It provides a default compression speed of typically > 500 MB/s per core.
+Speed can traded for higher compression ratio, by increasing the compression level parameter.
+While decompression is single-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound.
+`lz4` native file format is the `.lz4` format.
 
 ### Difference between lz4 and gzip
 
@@ -59,7 +57,7 @@
   * Similarly, `lz4 -m -d` can decompress multiple `*.lz4` files.
   * It's possible to opt-in to erase source files
     on successful compression or decompression, using `--rm` command.
-  * Consequently, `lz4 -m --rm` behaves the same as `gzip`.
+  * Consequently, `lz4 -m --rm` features a behavior closer to the `gzip` one.
 
 ### Concatenation of .lz4 files
 
@@ -115,7 +113,8 @@
 
 * `--list`:
   List information about .lz4 files.
-  note : current implementation is limited to single-frame .lz4 files.
+  For detailed information on files with multiple frames, use `-v`.
+  `--list` automatically triggers `-m` modifier.
 
 ### Operation modifiers
 
@@ -138,6 +137,10 @@
 * `--best`:
   Set highest compression level. Same as -12.
 
+* `-T#`, `--threads=#`:
+  Use `#` threads for compression.
+  When `0`, or none provided: automatically determined from nb of detected cores.
+
 * `--favor-decSpeed`:
   Generate compressed data optimized for decompression speed.
   Compressed data will be larger as a consequence (typically by ~0.5%),
@@ -244,6 +247,20 @@
   Minimum evaluation time in seconds \[1-9\] (default : 3)
 
 
+### Environment Variables
+
+It's possible to pass some parameters to `lz4` via environment variables.
+This can be useful in situations where `lz4` is known to be invoked (from a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
+The environment variable has higher priority than executable default, but lower priority than corresponding runtime command.
+When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones.
+
+* `LZ4_CLEVEL`:
+  specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
+
+* `LZ4_NBWORKERS`:
+  specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
+
+
 BUGS
 ----
 
diff --git a/programs/lz4cli.c b/programs/lz4cli.c
index 8c3f9fd..ccba8f1 100644
--- a/programs/lz4cli.c
+++ b/programs/lz4cli.c
@@ -1,6 +1,6 @@
 /*
   LZ4cli - LZ4 Command Line Interface
-  Copyright (C) Yann Collet 2011-2020
+  Copyright (C) Yann Collet 2011-2023
 
   GPL v2 License
 
@@ -31,6 +31,14 @@
 */
 
 
+/*-************************************
+*  Compiler options
+**************************************/
+#ifdef _MSC_VER    /* Visual Studio */
+#  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
+#endif
+
+
 /****************************
 *  Includes
 *****************************/
@@ -39,6 +47,7 @@
 #include <stdio.h>    /* fprintf, getchar */
 #include <stdlib.h>   /* exit, calloc, free */
 #include <string.h>   /* strcmp, strlen */
+#include "lz4conf.h"  /* compile-time constants */
 #include "bench.h"    /* BMK_benchFile, BMK_SetNbIterations, BMK_SetBlocksize, BMK_SetPause */
 #include "lz4io.h"    /* LZ4IO_compressFilename, LZ4IO_decompressFilename, LZ4IO_compressMultipleFilenames */
 #include "lz4hc.h"    /* LZ4HC_CLEVEL_MAX */
@@ -48,9 +57,14 @@
 /*****************************
 *  Constants
 ******************************/
-#define COMPRESSOR_NAME "LZ4 command line interface"
+#if LZ4IO_MULTITHREAD
+# define IO_MT "multithread"
+#else
+# define IO_MT "single-thread"
+#endif
+#define COMPRESSOR_NAME "lz4"
 #define AUTHOR "Yann Collet"
-#define WELCOME_MESSAGE "*** %s %i-bits v%s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(void*)*8), LZ4_versionString(), AUTHOR
+#define WELCOME_MESSAGE "*** %s v%s %i-bit %s, by %s ***\n", COMPRESSOR_NAME, LZ4_versionString(), (int)(sizeof(void*)*8), IO_MT, AUTHOR
 #define LZ4_EXTENSION ".lz4"
 #define LZ4CAT "lz4cat"
 #define UNLZ4 "unlz4"
@@ -61,30 +75,35 @@
 #define MB *(1U<<20)
 #define GB *(1U<<30)
 
-#define LZ4_BLOCKSIZEID_DEFAULT 7
-
 
 /*-************************************
 *  Macros
 ***************************************/
 #define DISPLAYOUT(...)        fprintf(stdout, __VA_ARGS__)
 #define DISPLAY(...)           fprintf(stderr, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...)   if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYLEVEL(l, ...)   do { if (displayLevel>=l) DISPLAY(__VA_ARGS__); } while (0)
 static unsigned displayLevel = 2;   /* 0 : no display ; 1: errors only ; 2 : downgradable normal ; 3 : non-downgradable normal; 4 : + information */
 
 
 /*-************************************
-*  Exceptions
+*  Errors and Messages
 ***************************************/
-#define DEBUG 0
-#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
-#define EXM_THROW(error, ...)                                             \
-{                                                                         \
-    DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
-    DISPLAYLEVEL(1, "Error %i : ", error);                                \
-    DISPLAYLEVEL(1, __VA_ARGS__);                                         \
-    DISPLAYLEVEL(1, "\n");                                                \
-    exit(error);                                                          \
+#ifndef DEBUG
+#  define DEBUG 0
+#endif
+#define DEBUGOUTPUT(...) do { if (DEBUG) DISPLAY(__VA_ARGS__); } while (0)
+#define END_PROCESS(error, ...)                                   \
+do {                                                              \
+    DEBUGOUTPUT("Error in %s, line %i : \n", __FILE__, __LINE__); \
+    DISPLAYLEVEL(1, "Error %i : ", error);                        \
+    DISPLAYLEVEL(1, __VA_ARGS__);                                 \
+    DISPLAYLEVEL(1, "\n");                                        \
+    exit(error);                                                  \
+} while (0)
+
+static void errorOut(const char* msg)
+{
+    DISPLAYLEVEL(1, "%s \n", msg); exit(1);
 }
 
 
@@ -110,11 +129,10 @@
     DISPLAY( "input   : a filename \n");
     DISPLAY( "          with no FILE, or when FILE is - or %s, read standard input\n", stdinmark);
     DISPLAY( "Arguments : \n");
-    DISPLAY( " -1     : Fast compression (default) \n");
-    DISPLAY( " -9     : High compression \n");
+    DISPLAY( " -1     : fast compression (default) \n");
+    DISPLAY( " -%2d    : slowest compression level \n", LZ4HC_CLEVEL_MAX);
+    DISPLAY( " -T#    : use # threads for compression (default:%i==auto) \n", LZ4_NBWORKERS_DEFAULT);
     DISPLAY( " -d     : decompression (default for %s extension)\n", LZ4_EXTENSION);
-    DISPLAY( " -z     : force compression \n");
-    DISPLAY( " -D FILE: use FILE as dictionary \n");
     DISPLAY( " -f     : overwrite output without prompting \n");
     DISPLAY( " -k     : preserve source files(s)  (default) \n");
     DISPLAY( "--rm    : remove source file(s) after successful de/compression \n");
@@ -138,8 +156,10 @@
     DISPLAY( " -r     : operate recursively on directories (sets also -m) \n");
 #endif
     DISPLAY( " -l     : compress using Legacy format (Linux kernel compression)\n");
+    DISPLAY( " -z     : force compression \n");
+    DISPLAY( " -D FILE: use FILE as dictionary (compression & decompression)\n");
     DISPLAY( " -B#    : cut file into blocks of size # bytes [32+] \n");
-    DISPLAY( "                     or predefined block size [4-7] (default: 7) \n");
+    DISPLAY( "                     or predefined block size [4-7] (default: %i) \n", LZ4_BLOCKSIZEID_DEFAULT);
     DISPLAY( " -BI    : Block Independence (default) \n");
     DISPLAY( " -BD    : Block dependency (improves compression ratio) \n");
     DISPLAY( " -BX    : enable block checksum (default:disabled) \n");
@@ -279,6 +299,34 @@
     return result;
 }
 
+#define CLEAN_RETURN(i) { operationResult = (i); goto _cleanup; }
+
+#define NEXT_FIELD(ptr) {         \
+    if (*argument == '=') {       \
+        ptr = ++argument;         \
+        argument += strlen(ptr);  \
+    } else {                      \
+        argNb++;                  \
+        if (argNb >= argCount) {  \
+            DISPLAYLEVEL(1, "error: missing command argument \n"); \
+            CLEAN_RETURN(1);      \
+        }                         \
+        ptr = argv[argNb];        \
+        assert(ptr != NULL);      \
+        if (ptr[0]=='-') {        \
+            DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
+            CLEAN_RETURN(1);      \
+}   }   }
+
+#define NEXT_UINT32(val32) {      \
+    const char* __nb;             \
+    NEXT_FIELD(__nb);             \
+    val32 = readU32FromChar(&__nb); \
+    if(*__nb != 0) {              \
+        errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
+    }                             \
+}
+
 /** longCommandWArg() :
  *  check if *stringPtr is the same as longCommand.
  *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
@@ -307,10 +355,40 @@
     else return om_compress;
 }
 
-int main(int argc, const char** argv)
+#define ENV_NBTHREADS "LZ4_NBWORKERS"
+
+static unsigned init_nbWorkers(void)
 {
-    int i,
-        cLevel=1,
+    const char* const env = getenv(ENV_NBTHREADS);
+    if (env != NULL) {
+        const char* ptr = env;
+        if ((*ptr>='0') && (*ptr<='9')) {
+            return readU32FromChar(&ptr);
+        }
+        DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
+    }
+    return LZ4_NBWORKERS_DEFAULT;
+}
+
+#define ENV_CLEVEL "LZ4_CLEVEL"
+
+static int init_cLevel(void)
+{
+    const char* const env = getenv(ENV_CLEVEL);
+    if (env != NULL) {
+        const char* ptr = env;
+        if ((*ptr>='0') && (*ptr<='9')) {
+            return (int)readU32FromChar(&ptr);
+        }
+        DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_CLEVEL, env);
+    }
+    return LZ4_CLEVEL_DEFAULT;
+}
+
+int main(int argCount, const char** argv)
+{
+    int argNb,
+        cLevel=init_cLevel(),
         cLevelLast=-10000,
         legacy_format=0,
         forceStdout=0,
@@ -319,12 +397,13 @@
         multiple_inputs=0,
         all_arguments_are_files=0,
         operationResult=0;
+    unsigned nbWorkers = init_nbWorkers();
     operationMode_e mode = om_auto;
     const char* input_filename = NULL;
     const char* output_filename= NULL;
     const char* dictionary_filename = NULL;
     char* dynNameSpace = NULL;
-    const char** inFileNames = (const char**)calloc((size_t)argc, sizeof(char*));
+    const char** inFileNames = (const char**)calloc((size_t)argCount, sizeof(char*));
     unsigned ifnIdx=0;
     LZ4IO_prefs_t* const prefs = LZ4IO_defaultPreferences();
     const char nullOutput[] = NULL_OUTPUT;
@@ -339,7 +418,8 @@
     /* Init */
     if (inFileNames==NULL) {
         DISPLAY("Allocation error : not enough memory \n");
-        return 1;
+        operationResult = 1;
+        goto _cleanup;
     }
     inFileNames[0] = stdinmark;
     LZ4IO_setOverwrite(prefs, 0);
@@ -359,8 +439,8 @@
     if (exeNameMatch(exeName, LZ4_LEGACY)) { g_lz4c_legacy_commands=1; }
 
     /* command switches */
-    for(i=1; i<argc; i++) {
-        const char* argument = argv[i];
+    for(argNb=1; argNb<argCount; argNb++) {
+        const char* argument = argv[argNb];
 
         if(!argument) continue;   /* Protection if argument empty */
 
@@ -382,7 +462,7 @@
                       if (mode != om_bench) mode = om_decompress;
                       BMK_setDecodeOnlyMode(1);
                       continue;
-                 }
+                  }
                 if (!strcmp(argument,  "--multiple")) { multiple_inputs = 1; continue; }
                 if (!strcmp(argument,  "--test")) { mode = om_test; continue; }
                 if (!strcmp(argument,  "--force")) { LZ4IO_setOverwrite(prefs, 1); continue; }
@@ -394,7 +474,7 @@
                 if (!strcmp(argument,  "--no-crc")) { LZ4IO_setStreamChecksumMode(prefs, 0); LZ4IO_setBlockChecksumMode(prefs, 0); BMK_skipChecksums(1); continue; }
                 if (!strcmp(argument,  "--content-size")) { LZ4IO_setContentSize(prefs, 1); continue; }
                 if (!strcmp(argument,  "--no-content-size")) { LZ4IO_setContentSize(prefs, 0); continue; }
-                if (!strcmp(argument,  "--list")) { mode = om_list; continue; }
+                if (!strcmp(argument,  "--list")) { mode = om_list; multiple_inputs = 1; continue; }
                 if (!strcmp(argument,  "--sparse")) { LZ4IO_setSparseFile(prefs, 2); continue; }
                 if (!strcmp(argument,  "--no-sparse")) { LZ4IO_setSparseFile(prefs, 0); continue; }
                 if (!strcmp(argument,  "--favor-decSpeed")) { LZ4IO_favorDecSpeed(prefs, 1); continue; }
@@ -404,25 +484,30 @@
                 if (!strcmp(argument,  "--help")) { usage_advanced(exeName); goto _cleanup; }
                 if (!strcmp(argument,  "--keep")) { LZ4IO_setRemoveSrcFile(prefs, 0); continue; }   /* keep source file (default) */
                 if (!strcmp(argument,  "--rm")) { LZ4IO_setRemoveSrcFile(prefs, 1); continue; }
+
+                if (longCommandWArg(&argument, "--threads")) {
+                    NEXT_UINT32(nbWorkers);
+                    continue;
+                }
                 if (longCommandWArg(&argument, "--fast")) {
-                        /* Parse optional acceleration factor */
-                        if (*argument == '=') {
-                            U32 fastLevel;
-                            ++argument;
-                            fastLevel = readU32FromChar(&argument);
-                            if (fastLevel) {
-                              cLevel = -(int)fastLevel;
-                            } else {
-                              badusage(exeName);
-                            }
-                        } else if (*argument != 0) {
-                            /* Invalid character following --fast */
-                            badusage(exeName);
+                    /* Parse optional acceleration factor */
+                    if (*argument == '=') {
+                        U32 fastLevel;
+                        ++argument;
+                        fastLevel = readU32FromChar(&argument);
+                        if (fastLevel) {
+                            cLevel = -(int)fastLevel;
                         } else {
-                            cLevel = -1;  /* default for --fast */
+                            badusage(exeName);
                         }
-                        continue;
+                    } else if (*argument != 0) {
+                        /* Invalid character following --fast */
+                        badusage(exeName);
+                    } else {
+                        cLevel = -1;  /* default for --fast */
                     }
+                    continue;
+                }
 
                 /* For gzip(1) compatibility */
                 if (!strcmp(argument,  "--best")) { cLevel=LZ4HC_CLEVEL_MAX; continue; }
@@ -463,14 +548,22 @@
                     /* Compression (default) */
                 case 'z': mode = om_compress; break;
 
+                    /* Modify Nb Worker threads (compression only) */
+                case 'T':
+                    {   argument++;
+                        nbWorkers = readU32FromChar(&argument);
+                        argument--;
+                    }
+                    break;
+
                 case 'D':
                     if (argument[1] == '\0') {
                         /* path is next arg */
-                        if (i + 1 == argc) {
+                        if (argNb + 1 == argCount) {
                             /* there is no next arg */
                             badusage(exeName);
                         }
-                        dictionary_filename = argv[++i];
+                        dictionary_filename = argv[++argNb];
                     } else {
                         /* path follows immediately */
                         dictionary_filename = argument + 1;
@@ -620,10 +713,16 @@
     DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
 #endif
 #ifdef _FILE_OFFSET_BITS
-    DISPLAYLEVEL(4, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS);
+    DISPLAYLEVEL(5, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS);
 #endif
-    if ((mode == om_compress) || (mode == om_bench))
+#if !LZ4IO_MULTITHREAD
+    if (nbWorkers > 1) {
+        DISPLAYLEVEL(2, "warning: this executable doesn't support multithreading \n");
+    }
+#endif
+    if ((mode == om_compress) || (mode == om_bench)) {
         DISPLAYLEVEL(4, "Blocks size : %u KB\n", (U32)(blockSize>>10));
+    }
 
     if (multiple_inputs) {
         input_filename = inFileNames[0];
@@ -676,16 +775,7 @@
     }
 
     /* No output filename ==> try to select one automatically (when possible) */
-    while ((!output_filename) && (multiple_inputs==0)) {
-        if (!IS_CONSOLE(stdout) && mode != om_list) {
-            /* Default to stdout whenever stdout is not the console.
-             * Note : this policy may change in the future, therefore don't rely on it !
-             * To ensure `stdout` is explicitly selected, use `-c` command flag.
-             * Conversely, to ensure output will not become `stdout`, use `-m` command flag */
-            DISPLAYLEVEL(1, "Warning : using stdout as default output. Do not rely on this behavior: use explicit `-c` instead ! \n");
-            output_filename = stdoutmark;
-            break;
-        }
+    if ((!output_filename) && (multiple_inputs==0)) {
         if (mode == om_auto) {  /* auto-determine compression or decompression, based on file extension */
             mode = determineOpMode(input_filename);
         }
@@ -697,9 +787,9 @@
             strcat(dynNameSpace, LZ4_EXTENSION);
             output_filename = dynNameSpace;
             DISPLAYLEVEL(2, "Compressed filename will be : %s \n", output_filename);
-            break;
         }
-        if (mode == om_decompress) {/* decompress to file (automatic output name only works if input filename has correct format extension) */
+        if (mode == om_decompress) {
+            /* decompress to file (automatic output name only works if input filename has correct format extension) */
             size_t outl;
             size_t const inl = strlen(input_filename);
             dynNameSpace = (char*)calloc(1,inl+1);
@@ -712,7 +802,6 @@
             output_filename = dynNameSpace;
             DISPLAYLEVEL(2, "Decoding file %s \n", output_filename);
         }
-        break;
     }
 
     if (mode == om_list) {
@@ -757,13 +846,27 @@
     } else if (mode == om_list){
         operationResult = LZ4IO_displayCompressedFilesInfo(inFileNames, ifnIdx);
     } else {   /* compression is default action */
+#if LZ4IO_MULTITHREAD
+        if (nbWorkers != 1) {
+            if (nbWorkers==0)
+                nbWorkers = (unsigned)LZ4IO_defaultNbWorkers();
+            if (nbWorkers > LZ4_NBWORKERS_MAX) {
+                DISPLAYLEVEL(3, "Requested %u threads too large => automatically reduced to %u \n",
+                            nbWorkers, LZ4_NBWORKERS_MAX);
+                nbWorkers = LZ4_NBWORKERS_MAX;
+            } else {
+                DISPLAYLEVEL(3, "Using %u threads for compression \n", nbWorkers);
+            }
+        }
+        LZ4IO_setNbWorkers(prefs, (int)nbWorkers);
+#endif
         if (legacy_format) {
             DISPLAYLEVEL(3, "! Generating LZ4 Legacy format (deprecated) ! \n");
             if(multiple_inputs){
                 const char* const leg_extension = !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION;
-                LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
+                operationResult = LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
             } else {
-                LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
+                operationResult = LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
             }
         } else {
             if (multiple_inputs) {
diff --git a/programs/lz4conf.h b/programs/lz4conf.h
new file mode 100644
index 0000000..93e09ae
--- /dev/null
+++ b/programs/lz4conf.h
@@ -0,0 +1,71 @@
+/*
+  LZ4conf.h - compile-time parameters
+  Copyright (C) Yann Collet 2011-2024
+  GPL v2 License
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License along
+  with this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  You can contact the author at :
+  - LZ4 source repository : https://github.com/lz4/lz4
+  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+#ifndef LZ4CONF_H_32432
+#define LZ4CONF_H_32432
+
+
+/* Default compression level.
+ * Can be overridden by environment variable LZ4_CLEVEL.
+ * Can be overridden at runtime using -# command */
+#ifndef LZ4_CLEVEL_DEFAULT
+# define LZ4_CLEVEL_DEFAULT 1
+#endif
+
+/* Determines if multithreading is enabled or not
+ * Default: disabled */
+#ifndef LZ4IO_MULTITHREAD
+# ifdef _WIN32
+    /* Windows support Completion Ports */
+#   define LZ4IO_MULTITHREAD 1
+# else
+    /* Requires <pthread> support.
+     * Can't be reliably and portably tested at source code level */
+#   define LZ4IO_MULTITHREAD 0
+# endif
+#endif
+
+/* Determines default nb of threads for compression
+ * Default value is 0, which means "auto" :
+ * nb of threads is determined from detected local cpu.
+ * Can be overriden by Environment Variable LZ4_NBWORKERS.
+ * Can be overridden at runtime using -T# command */
+#ifndef LZ4_NBWORKERS_DEFAULT
+# define LZ4_NBWORKERS_DEFAULT 0
+#endif
+
+/* Maximum nb of compression threads selectable at runtime */
+#ifndef LZ4_NBWORKERS_MAX
+# define LZ4_NBWORKERS_MAX 200
+#endif
+
+/* Determines default lz4 block size when none provided.
+ * Default value is 7, which represents 4 MB.
+ * Can be overridden at runtime using -B# command */
+#ifndef LZ4_BLOCKSIZEID_DEFAULT
+# define LZ4_BLOCKSIZEID_DEFAULT 7
+#endif
+
+
+#endif  /* LZ4CONF_H_32432 */
diff --git a/programs/lz4io.c b/programs/lz4io.c
index 8b70b91..17274e2 100644
--- a/programs/lz4io.c
+++ b/programs/lz4io.c
@@ -1,6 +1,6 @@
 /*
   LZ4io.c - LZ4 File/Stream Interface
-  Copyright (C) Yann Collet 2011-2020
+  Copyright (C) Yann Collet 2011-2024
 
   GPL v2 License
 
@@ -46,18 +46,21 @@
 *  Includes
 *****************************/
 #include "platform.h"  /* Large File Support, SET_BINARY_MODE, SET_SPARSE_FILE_MODE, PLATFORM_POSIX_VERSION, __64BIT__ */
+#include "timefn.h"    /* TIME_ */
 #include "util.h"      /* UTIL_getFileStat, UTIL_setFileStat */
 #include <stdio.h>     /* fprintf, fopen, fread, stdin, stdout, fflush, getchar */
 #include <stdlib.h>    /* malloc, free */
 #include <string.h>    /* strerror, strcmp, strlen */
-#include <time.h>      /* clock */
+#include <time.h>      /* clock_t, for cpu-time */
 #include <sys/types.h> /* stat64 */
 #include <sys/stat.h>  /* stat64 */
-#include "lz4.h"       /* still required for legacy format */
-#include "lz4hc.h"     /* still required for legacy format */
-#define LZ4F_STATIC_LINKING_ONLY
-#include "lz4frame.h"
+#include "lz4conf.h"   /* compile-time constants */
 #include "lz4io.h"
+#include "lz4.h"       /* required for legacy format */
+#include "lz4hc.h"     /* required for legacy format */
+#define LZ4F_STATIC_LINKING_ONLY
+#include "lz4frame.h"  /* LZ4F_* */
+#include "xxhash.h"    /* frame checksum (MT mode) */
 
 
 /*****************************
@@ -85,27 +88,57 @@
 #define LZ4IO_BLOCKSIZEID_DEFAULT 7
 #define LZ4_MAX_DICT_SIZE (64 KB)
 
+#undef MIN
+#define MIN(a,b)  ((a)<(b)?(a):(b))
 
 /**************************************
-*  Macros
+*  Time and Display
 **************************************/
 #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
 #define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); if (g_displayLevel>=4) fflush(stderr); }
 static int g_displayLevel = 0;   /* 0 : no display  ; 1: errors  ; 2 : + result + interaction + warnings ; 3 : + progression; 4 : + information */
 
 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
-            if ( ((clock() - g_time) > refreshRate)    \
+            if ( (TIME_clockSpan_ns(g_time) > refreshRate)  \
               || (g_displayLevel>=4) ) {               \
-                g_time = clock();                      \
+                g_time = TIME_getTime();               \
                 DISPLAY(__VA_ARGS__);                  \
                 if (g_displayLevel>=4) fflush(stderr); \
         }   }
-static const clock_t refreshRate = CLOCKS_PER_SEC / 6;
-static clock_t g_time = 0;
+static const Duration_ns refreshRate = 200000000;
+static TIME_t g_time = { 0 };
 
-#define LZ4IO_STATIC_ASSERT(c)   { enum { LZ4IO_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
+static double cpuLoad_sec(clock_t cpuStart)
+{
+#ifdef _WIN32
+    FILETIME creationTime, exitTime, kernelTime, userTime;
+    (void)cpuStart;
+    GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime);
+    assert(kernelTime.dwHighDateTime == 0);
+    assert(userTime.dwHighDateTime == 0);
+    return ((double)kernelTime.dwLowDateTime + (double)userTime.dwLowDateTime) * 100. / 1000000000.;
+#else
+    return (double)(clock() - cpuStart) / CLOCKS_PER_SEC;
+#endif
+}
 
+static void LZ4IO_finalTimeDisplay(TIME_t timeStart, clock_t cpuStart, unsigned long long size)
+{
+#if LZ4IO_MULTITHREAD
+    if (!TIME_support_MT_measurements()) {
+        DISPLAYLEVEL(5, "time measurements not compatible with multithreading \n");
+    } else
+#endif
+    {
+        Duration_ns duration_ns = TIME_clockSpan_ns(timeStart);
+        double const seconds = (double)(duration_ns + !duration_ns) / (double)1000000000.;
+        double const cpuLoad_s = cpuLoad_sec(cpuStart);
+        DISPLAYLEVEL(3,"Done in %.2f s ==> %.2f MiB/s  (cpu load : %.0f%%)\n", seconds,
+                        (double)size / seconds / 1024. / 1024.,
+                        (cpuLoad_s / seconds) * 100.);
+    }
+}
 
 /**************************************
 *  Exceptions
@@ -114,15 +147,34 @@
 #  define DEBUG 0
 #endif
 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
-#define END_PROCESS(error, ...)                                           \
-{                                                                         \
-    DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
-    DISPLAYLEVEL(1, "Error %i : ", error);                                \
-    DISPLAYLEVEL(1, __VA_ARGS__);                                         \
-    DISPLAYLEVEL(1, " \n");                                               \
-    exit(error);                                                          \
+#define END_PROCESS(error, ...)                                   \
+{                                                                 \
+    DEBUGOUTPUT("Error in %s, line %i : \n", __FILE__, __LINE__); \
+    DISPLAYLEVEL(1, "Error %i : ", error);                        \
+    DISPLAYLEVEL(1, __VA_ARGS__);                                 \
+    DISPLAYLEVEL(1, " \n");                                       \
+    fflush(NULL);                                                 \
+    exit(error);                                                  \
 }
 
+#define LZ4IO_STATIC_ASSERT(c)   { enum { LZ4IO_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
+
+
+/* ************************************************** */
+/* ****************** Init functions ******************** */
+/* ************************************************** */
+
+int LZ4IO_defaultNbWorkers(void)
+{
+#if LZ4IO_MULTITHREAD
+    int const nbCores = UTIL_countCores();
+    int const spared = 1 + ((unsigned)nbCores >> 3);
+    if (nbCores <= spared) return 1;
+    return nbCores - spared;
+#else
+    return 1;
+#endif
+}
 
 /* ************************************************** */
 /* ****************** Parameters ******************** */
@@ -143,34 +195,43 @@
     unsigned favorDecSpeed;
     const char* dictionaryFilename;
     int removeSrcFile;
+    int nbWorkers;
 };
 
-LZ4IO_prefs_t* LZ4IO_defaultPreferences(void)
-{
-    LZ4IO_prefs_t* const ret = (LZ4IO_prefs_t*)malloc(sizeof(*ret));
-    if (!ret) END_PROCESS(21, "Allocation error : not enough memory");
-    ret->passThrough = 0;
-    ret->overwrite = 1;
-    ret->testMode = 0;
-    ret->blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT;
-    ret->blockSize = 0;
-    ret->blockChecksum = 0;
-    ret->streamChecksum = 1;
-    ret->blockIndependence = 1;
-    ret->sparseFileSupport = 1;
-    ret->contentSizeFlag = 0;
-    ret->useDictionary = 0;
-    ret->favorDecSpeed = 0;
-    ret->dictionaryFilename = NULL;
-    ret->removeSrcFile = 0;
-    return ret;
-}
-
 void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs)
 {
     free(prefs);
 }
 
+LZ4IO_prefs_t* LZ4IO_defaultPreferences(void)
+{
+    LZ4IO_prefs_t* const prefs = (LZ4IO_prefs_t*)malloc(sizeof(*prefs));
+    if (!prefs) END_PROCESS(11, "Can't even allocate LZ4IO preferences");
+    prefs->passThrough = 0;
+    prefs->overwrite = 1;
+    prefs->testMode = 0;
+    prefs->blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT;
+    prefs->blockSize = 0;
+    prefs->blockChecksum = 0;
+    prefs->streamChecksum = 1;
+    prefs->blockIndependence = 1;
+    prefs->sparseFileSupport = 1;
+    prefs->contentSizeFlag = 0;
+    prefs->useDictionary = 0;
+    prefs->favorDecSpeed = 0;
+    prefs->dictionaryFilename = NULL;
+    prefs->removeSrcFile = 0;
+    prefs->nbWorkers = LZ4IO_defaultNbWorkers();
+    return prefs;
+}
+
+int LZ4IO_setNbWorkers(LZ4IO_prefs_t* const prefs, int nbWorkers)
+{
+    if (nbWorkers < 1 ) nbWorkers = 1;
+    nbWorkers = MIN(nbWorkers, LZ4_NBWORKERS_MAX);
+    prefs->nbWorkers = nbWorkers;
+    return nbWorkers;
+}
 
 int LZ4IO_setDictionaryFilename(LZ4IO_prefs_t* const prefs, const char* dictionaryFilename)
 {
@@ -186,7 +247,6 @@
    return prefs->passThrough;
 }
 
-
 /* Default setting : overwrite = 1; return : overwrite mode (0/1) */
 int LZ4IO_setOverwrite(LZ4IO_prefs_t* const prefs, int yes)
 {
@@ -284,7 +344,6 @@
 }
 
 
-
 /* ************************************************************************ **
 ** ********************** String functions ********************* **
 ** ************************************************************************ */
@@ -325,11 +384,16 @@
         DISPLAYLEVEL(4,"Using stdin for input \n");
         f = stdin;
         SET_BINARY_MODE(stdin);
-    } else {
-        f = fopen(srcFileName, "rb");
-        if (f==NULL) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno));
+        return f;
     }
 
+    if (UTIL_isDirectory(srcFileName)) {
+        DISPLAYLEVEL(1, "lz4: %s is a directory -- ignored \n", srcFileName);
+        return NULL;
+    }
+
+    f = fopen(srcFileName, "rb");
+    if (f==NULL) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno));
     return f;
 }
 
@@ -337,7 +401,8 @@
  *  prefs is writable, because sparseFileSupport might be updated.
  *  condition : `dstFileName` must be non-NULL.
  * @result : FILE* to `dstFileName`, or NULL if it fails */
-static FILE* LZ4IO_openDstFile(const char* dstFileName, const LZ4IO_prefs_t* const prefs)
+static FILE*
+LZ4IO_openDstFile(const char* dstFileName, const LZ4IO_prefs_t* const prefs)
 {
     FILE* f;
     assert(dstFileName != NULL);
@@ -381,6 +446,311 @@
 }
 
 
+/***************************************
+*   MT I/O
+***************************************/
+
+#include "threadpool.h"
+
+typedef struct {
+    void* buf;
+    size_t size;
+    unsigned long long rank;
+} BufferDesc;
+
+typedef struct {
+    unsigned long long expectedRank;
+    BufferDesc* buffers;
+    size_t capacity;
+    size_t blockSize;
+    unsigned long long totalCSize;
+} WriteRegister;
+
+static void WR_destroy(WriteRegister* wr)
+{
+    free(wr->buffers);
+}
+
+#define WR_INITIAL_BUFFER_POOL_SIZE 16
+/* Note: WR_init() can fail (allocation)
+ * check that wr->buffers!= NULL for success */
+static WriteRegister WR_init(size_t blockSize)
+{
+    WriteRegister wr = { 0, NULL, WR_INITIAL_BUFFER_POOL_SIZE, 0, 0 };
+    wr.buffers = (BufferDesc*)calloc(1, WR_INITIAL_BUFFER_POOL_SIZE * sizeof(BufferDesc));
+    wr.blockSize = blockSize;
+    return wr;
+}
+
+static void WR_addBufDesc(WriteRegister* wr, const BufferDesc* bd)
+{
+    if (wr->buffers[wr->capacity-1].buf != NULL) {
+        /* buffer capacity is full : extend it */
+        size_t const oldCapacity = wr->capacity;
+        size_t const addedCapacity = MIN(oldCapacity, 256);
+        size_t const newCapacity = oldCapacity + addedCapacity;
+        size_t const newSize = newCapacity * sizeof(BufferDesc);
+        void* const newBuf = realloc(wr->buffers, newSize);
+        if (newBuf == NULL) {
+            END_PROCESS(39, "cannot extend register of buffers")
+        }
+        wr->buffers = (BufferDesc*)newBuf;
+        memset(wr->buffers + oldCapacity, 0, addedCapacity * sizeof(BufferDesc));
+        wr->buffers[oldCapacity] = bd[0];
+        wr->capacity = newCapacity;
+    } else {
+        /* at least one position (the last one) is free, i.e. buffer==NULL */
+        size_t n;
+        for (n=0; n<wr->capacity; n++) {
+            if (wr->buffers[n].buf == NULL) {
+                wr->buffers[n] = bd[0];
+                break;
+            }
+        }
+        assert(n != wr->capacity);
+    }
+}
+
+static int WR_isPresent(WriteRegister* wr, unsigned long long id)
+{
+    size_t n;
+    for (n=0; n<wr->capacity; n++) {
+        if (wr->buffers[n].buf == NULL) {
+            /* no more buffers stored */
+            return 0;
+        }
+        if (wr->buffers[n].rank == id)
+            return 1;
+    }
+    return 0;
+}
+
+/* Note: requires @id to exist! */
+static BufferDesc WR_getBufID(WriteRegister* wr, unsigned long long id)
+{
+    size_t n;
+    for (n=0; n<wr->capacity; n++) {
+        if (wr->buffers[n].buf == NULL) {
+            /* no more buffers stored */
+            break;
+        }
+        if (wr->buffers[n].rank == id)
+            return wr->buffers[n];
+    }
+    END_PROCESS(41, "buffer ID not found");
+}
+
+static void WR_removeBuffID(WriteRegister* wr, unsigned long long id)
+{
+    size_t n;
+    for (n=0; n<wr->capacity; n++) {
+        if (wr->buffers[n].buf == NULL) {
+            /* no more buffers stored */
+            return;
+        }
+        if (wr->buffers[n].rank == id) {
+            free(wr->buffers[n].buf);
+            break;
+        }
+    }
+    /* overwrite buffer descriptor, scale others down*/
+    n++;
+    for (; n < wr->capacity; n++) {
+        wr->buffers[n-1] = wr->buffers[n];
+        if (wr->buffers[n].buf == NULL)
+            return;
+    }
+    {   BufferDesc const nullBd = { NULL, 0, 0 };
+        wr->buffers[wr->capacity-1] = nullBd;
+    }
+}
+
+typedef struct {
+    WriteRegister* wr;
+    void* cBuf;
+    size_t cSize;
+    unsigned long long blockNb;
+    FILE* out;
+} WriteJobDesc;
+
+static void LZ4IO_writeBuffer(BufferDesc bufDesc, FILE* out)
+{
+    size_t const size = bufDesc.size;
+    if (fwrite(bufDesc.buf, 1, size, out) != size) {
+        END_PROCESS(38, "Write error : cannot write compressed block");
+    }
+}
+
+static void LZ4IO_checkWriteOrder(void* arg)
+{
+    WriteJobDesc* const wjd = (WriteJobDesc*)arg;
+    size_t const cSize = wjd->cSize;
+    WriteRegister* const wr = wjd->wr;
+
+    if (wjd->blockNb != wr->expectedRank) {
+        /* incorrect order : let's store this buffer for later write */
+        BufferDesc bd;
+        bd.buf = wjd->cBuf;
+        bd.size = wjd->cSize;
+        bd.rank = wjd->blockNb;
+        WR_addBufDesc(wr, &bd);
+        free(wjd);  /* because wjd is pod */
+        return;
+    }
+
+    /* expected block ID : let's write this block */
+    {   BufferDesc bd;
+        bd.buf = wjd->cBuf;
+        bd.size = wjd->cSize;
+        bd.rank = wjd->blockNb;
+        LZ4IO_writeBuffer(bd, wjd->out);
+    }
+    wr->expectedRank++;
+    wr->totalCSize += cSize;
+    free(wjd->cBuf);
+    /* and check for more blocks, previously saved */
+    while (WR_isPresent(wr, wr->expectedRank)) {
+        BufferDesc const bd = WR_getBufID(wr, wr->expectedRank);
+        LZ4IO_writeBuffer(bd, wjd->out);
+        wr->totalCSize += bd.size;
+        WR_removeBuffID(wr, wr->expectedRank);
+        wr->expectedRank++;
+    }
+    free(wjd);  /* because wjd is pod */
+    {   unsigned long long const processedSize = (unsigned long long)(wr->expectedRank-1) * wr->blockSize;
+        DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
+                (unsigned)(processedSize >> 20),
+                (double)wr->totalCSize / (double)processedSize * 100.);
+    }
+}
+
+typedef size_t (*compress_f)(
+    const void* parameters,
+    void* dst,
+    size_t dstCapacity,
+    const void* src,
+    size_t srcSize,
+    size_t prefixSize);
+
+typedef struct {
+    TPool* wpool;
+    void* buffer;
+    size_t prefixSize;
+    size_t inSize;
+    unsigned long long blockNb;
+    compress_f compress;
+    const void* compressParameters;
+    FILE* fout;
+    WriteRegister* wr;
+    size_t maxCBlockSize;
+    int lastBlock;
+} CompressJobDesc;
+
+static void LZ4IO_compressChunk(void* arg)
+{
+    CompressJobDesc* const cjd = (CompressJobDesc*)arg;
+    size_t const outCapacity = cjd->maxCBlockSize;
+    void* const out_buff = malloc(outCapacity);
+    if (!out_buff)
+        END_PROCESS(33, "Allocation error : can't allocate output buffer to compress new chunk");
+    {   char* const inBuff = (char*)cjd->buffer + cjd->prefixSize;
+        size_t const cSize = cjd->compress(cjd->compressParameters, out_buff, outCapacity, inBuff, cjd->inSize, cjd->prefixSize);
+
+        /* check for write */
+        {   WriteJobDesc* const wjd = (WriteJobDesc*)malloc(sizeof(*wjd));
+            if (wjd == NULL) {
+                END_PROCESS(35, "Allocation error : can't describe new write job");
+            }
+            wjd->cBuf = out_buff;
+            wjd->cSize = (size_t)cSize;
+            wjd->blockNb = cjd->blockNb;
+            wjd->out = cjd->fout;
+            wjd->wr = cjd->wr;
+            TPool_submitJob(cjd->wpool, LZ4IO_checkWriteOrder, wjd);
+    }   }
+}
+
+static void LZ4IO_compressAndFreeChunk(void* arg)
+{
+    CompressJobDesc* const cjd = (CompressJobDesc*)arg;
+    LZ4IO_compressChunk(arg);
+    /* clean up */
+    free(cjd->buffer);
+    free(cjd); /* because cjd is pod */
+}
+
+/* one ReadTracker per file to compress */
+typedef struct {
+    TPool* tPool;
+    TPool* wpool;
+    FILE* fin;
+    size_t chunkSize;
+    unsigned long long totalReadSize;
+    unsigned long long blockNb;
+    XXH32_state_t* xxh32;
+    compress_f compress;
+    const void* compressParameters;
+    void* prefix; /* if it exists, assumed to be filled with 64 KB */
+    FILE* fout;
+    WriteRegister* wr;
+    size_t maxCBlockSize;
+} ReadTracker;
+
+static void LZ4IO_readAndProcess(void* arg)
+{
+    ReadTracker* const rjd = (ReadTracker*)arg;
+    size_t const chunkSize = rjd->chunkSize;
+    size_t const prefixSize = (rjd->prefix != NULL) * 64 KB;
+    size_t const bufferSize = chunkSize + prefixSize;
+    void* const buffer = malloc(bufferSize);
+    if (!buffer)
+        END_PROCESS(31, "Allocation error : can't allocate buffer to read new chunk");
+    if (prefixSize) {
+        assert(prefixSize == 64 KB);
+        memcpy(buffer, rjd->prefix, prefixSize);
+    }
+    {   char* const in_buff = (char*)buffer + prefixSize;
+        size_t const inSize = fread(in_buff, (size_t)1, chunkSize, rjd->fin);
+        if (inSize > chunkSize) {
+            END_PROCESS(32, "Read error (read %u > %u [chunk size])", (unsigned)inSize, (unsigned)chunkSize);
+        }
+        rjd->totalReadSize += inSize;
+        /* special case: nothing left: stop read operation */
+        if (inSize == 0) {
+            free(buffer);
+            return;
+        }
+        /* process read input */
+        {   CompressJobDesc* const cjd = (CompressJobDesc*)malloc(sizeof(*cjd));
+            if (cjd==NULL) {
+                END_PROCESS(33, "Allocation error : can't describe new compression job");
+            }
+            if (rjd->xxh32) {
+                XXH32_update(rjd->xxh32, in_buff, inSize);
+            }
+            if (rjd->prefix) {
+                /* dependent blocks mode */
+                memcpy(rjd->prefix, in_buff + inSize - 64 KB, 64 KB);
+            }
+            cjd->wpool = rjd->wpool;
+            cjd->buffer = buffer; /* transfer ownership */
+            cjd->prefixSize = prefixSize;
+            cjd->inSize = inSize;
+            cjd->blockNb = rjd->blockNb;
+            cjd->compress = rjd->compress;
+            cjd->compressParameters = rjd->compressParameters;
+            cjd->fout = rjd->fout;
+            cjd->wr = rjd->wr;
+            cjd->maxCBlockSize = rjd->maxCBlockSize;
+            cjd->lastBlock = inSize < chunkSize;
+            TPool_submitJob(rjd->tPool, LZ4IO_compressAndFreeChunk, cjd);
+            if (inSize == chunkSize) {
+                /* likely more => read another chunk */
+                rjd->blockNb++;
+                TPool_submitJob(rjd->tPool, LZ4IO_readAndProcess, rjd);
+    }   }   }
+}
+
 
 /***************************************
 *   Legacy Compression
@@ -400,95 +770,151 @@
     dstPtr[3] = (unsigned char)(value32 >> 24);
 }
 
-static int LZ4IO_LZ4_compress(const char* src, char* dst, int srcSize, int dstSize, int cLevel)
+
+typedef struct {
+    int cLevel;
+} CompressLegacyState;
+
+static size_t LZ4IO_compressBlockLegacy_fast(
+    const void* params,
+    void* dst,
+    size_t dstCapacity,
+    const void* src,
+    size_t srcSize,
+    size_t prefixSize
+)
 {
-    (void)cLevel;
-    return LZ4_compress_fast(src, dst, srcSize, dstSize, 1);
+    const CompressLegacyState* const clevel = (const CompressLegacyState*)params;
+    int const acceleration = (clevel->cLevel < 0) ? -clevel->cLevel : 0;
+    int const cSize = LZ4_compress_fast((const char*)src, (char*)dst + LZ4IO_LEGACY_BLOCK_HEADER_SIZE, (int)srcSize, (int)dstCapacity, acceleration);
+    if (cSize < 0)
+        END_PROCESS(51, "fast compression failed");
+    LZ4IO_writeLE32(dst, (unsigned)cSize);
+    assert(prefixSize == 0); (void)prefixSize;
+    return (size_t) cSize + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
+}
+
+static size_t LZ4IO_compressBlockLegacy_HC(
+    const void* params,
+    void* dst,
+    size_t dstCapacity,
+    const void* src,
+    size_t srcSize,
+    size_t prefixSize
+)
+{
+    const CompressLegacyState* const cs = (const CompressLegacyState*)params;
+    int const clevel = cs->cLevel;
+    int const cSize = LZ4_compress_HC((const char*)src, (char*)dst + LZ4IO_LEGACY_BLOCK_HEADER_SIZE, (int)srcSize, (int)dstCapacity, clevel);
+    if (cSize < 0)
+        END_PROCESS(52, "HC compression failed");
+    LZ4IO_writeLE32(dst, (unsigned)cSize);
+    assert(prefixSize == 0); (void)prefixSize;
+    return (size_t) cSize + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
+}
+
+/* LZ4IO_compressLegacy_internal :
+ * Implementation of LZ4IO_compressFilename_Legacy.
+ * @return: 0 if success, !0 if error
+ */
+static int LZ4IO_compressLegacy_internal(unsigned long long* readSize,
+                                  const char* input_filename,
+                                  const char* output_filename,
+                                  int compressionlevel,
+                                  const LZ4IO_prefs_t* prefs)
+{
+    int clResult = 0;
+    compress_f const compressionFunction = (compressionlevel < 3) ? LZ4IO_compressBlockLegacy_fast : LZ4IO_compressBlockLegacy_HC;
+    FILE* const finput = LZ4IO_openSrcFile(input_filename);
+    FILE* foutput = NULL;
+    TPool* const tPool = TPool_create(prefs->nbWorkers, 4);
+    TPool* const wPool = TPool_create(1, 4);
+    WriteRegister wr = WR_init(LEGACY_BLOCKSIZE);
+
+    /* Init & checks */
+    *readSize = 0;
+    if (finput == NULL) {
+        /* read file error : recoverable */
+        clResult = 1;
+        goto _cfl_clean;
+    }
+    foutput = LZ4IO_openDstFile(output_filename, prefs);
+    if (foutput == NULL) {
+        /* write file error : recoverable */
+        clResult = 1;
+        goto _cfl_clean;
+    }
+    if (tPool == NULL || wPool == NULL)
+        END_PROCESS(21, "threadpool creation error ");
+    if (wr.buffers == NULL)
+        END_PROCESS(22, "can't allocate write register");
+
+
+    /* Write Archive Header */
+    {   char outHeader[MAGICNUMBER_SIZE];
+        LZ4IO_writeLE32(outHeader, LEGACY_MAGICNUMBER);
+        if (fwrite(outHeader, 1, MAGICNUMBER_SIZE, foutput) != MAGICNUMBER_SIZE)
+            END_PROCESS(23, "Write error : cannot write header");
+    }
+    wr.totalCSize = MAGICNUMBER_SIZE;
+
+    {   CompressLegacyState cls;
+        ReadTracker rjd;
+        cls.cLevel = compressionlevel;
+        rjd.tPool = tPool;
+        rjd.wpool = wPool;
+        rjd.fin = finput;
+        rjd.chunkSize = LEGACY_BLOCKSIZE;
+        rjd.totalReadSize = 0;
+        rjd.blockNb = 0;
+        rjd.xxh32 = NULL;
+        rjd.compress = compressionFunction;
+        rjd.compressParameters = &cls;
+        rjd.prefix = NULL;
+        rjd.fout = foutput;
+        rjd.wr = &wr;
+        rjd.maxCBlockSize = (size_t)LZ4_compressBound(LEGACY_BLOCKSIZE) + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
+        /* Ignite the job chain */
+        TPool_submitJob(tPool, LZ4IO_readAndProcess, &rjd);
+        /* Wait for all completion */
+        TPool_jobsCompleted(tPool);
+        TPool_jobsCompleted(wPool);
+
+        /* Status */
+        DISPLAYLEVEL(2, "\r%79s\r", "");    /* blank line */
+        DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%% \n",
+                    rjd.totalReadSize, wr.totalCSize,
+                    (double)wr.totalCSize / (double)(rjd.totalReadSize + !rjd.totalReadSize) * 100.);
+        *readSize = rjd.totalReadSize;
+    }
+
+    /* Close & Free */
+_cfl_clean:
+    WR_destroy(&wr);
+    TPool_free(wPool);
+    TPool_free(tPool);
+    if (finput) fclose(finput);
+    if (foutput && !LZ4IO_isStdout(output_filename)) fclose(foutput);  /* do not close stdout */
+
+    return clResult;
 }
 
 /* LZ4IO_compressFilename_Legacy :
  * This function is intentionally "hidden" (not published in .h)
- * It generates compressed streams using the old 'legacy' format */
-int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename,
-                                  int compressionlevel, const LZ4IO_prefs_t* prefs)
+ * It generates compressed streams using the old 'legacy' format
+ * @return: 0 if success, !0 if error
+ */
+int LZ4IO_compressFilename_Legacy(const char* input_filename,
+                                  const char* output_filename,
+                                  int compressionlevel,
+                                  const LZ4IO_prefs_t* prefs)
 {
-    typedef int (*compress_f)(const char* src, char* dst, int srcSize, int dstSize, int cLevel);
-    compress_f const compressionFunction = (compressionlevel < 3) ? LZ4IO_LZ4_compress : LZ4_compress_HC;
-    unsigned long long filesize = 0;
-    unsigned long long compressedfilesize = MAGICNUMBER_SIZE;
-    char* in_buff;
-    char* out_buff;
-    const int outBuffSize = LZ4_compressBound(LEGACY_BLOCKSIZE);
-    FILE* const finput = LZ4IO_openSrcFile(input_filename);
-    FILE* foutput;
-    clock_t clockEnd;
-
-    /* Init */
-    clock_t const clockStart = clock();
-    if (finput == NULL)
-        END_PROCESS(20, "%s : open file error ", input_filename);
-
-    foutput = LZ4IO_openDstFile(output_filename, prefs);
-    if (foutput == NULL) {
-        fclose(finput);
-        END_PROCESS(20, "%s : open file error ", input_filename);
-    }
-
-    /* Allocate Memory */
-    in_buff = (char*)malloc(LEGACY_BLOCKSIZE);
-    out_buff = (char*)malloc((size_t)outBuffSize + 4);
-    if (!in_buff || !out_buff)
-        END_PROCESS(21, "Allocation error : not enough memory");
-
-    /* Write Archive Header */
-    LZ4IO_writeLE32(out_buff, LEGACY_MAGICNUMBER);
-    if (fwrite(out_buff, 1, MAGICNUMBER_SIZE, foutput) != MAGICNUMBER_SIZE)
-        END_PROCESS(22, "Write error : cannot write header");
-
-    /* Main Loop */
-    while (1) {
-        int outSize;
-        /* Read Block */
-        size_t const inSize = fread(in_buff, (size_t)1, (size_t)LEGACY_BLOCKSIZE, finput);
-        if (inSize == 0) break;
-        assert(inSize <= LEGACY_BLOCKSIZE);
-        filesize += inSize;
-
-        /* Compress Block */
-        outSize = compressionFunction(in_buff, out_buff+4, (int)inSize, outBuffSize, compressionlevel);
-        assert(outSize >= 0);
-        compressedfilesize += (unsigned long long)outSize+4;
-        DISPLAYUPDATE(2, "\rRead : %i MiB  ==> %.2f%%   ",
-                (int)(filesize>>20), (double)compressedfilesize/filesize*100);
-
-        /* Write Block */
-        assert(outSize > 0);
-        assert(outSize < outBuffSize);
-        LZ4IO_writeLE32(out_buff, (unsigned)outSize);
-        if (fwrite(out_buff, 1, (size_t)outSize+4, foutput) != (size_t)(outSize+4)) {
-            END_PROCESS(24, "Write error : cannot write compressed block");
-    }   }
-    if (ferror(finput)) END_PROCESS(24, "Error while reading %s ", input_filename);
-
-    /* Status */
-    clockEnd = clock();
-    clockEnd += (clockEnd==clockStart); /* avoid division by zero (speed) */
-    filesize += !filesize;   /* avoid division by zero (ratio) */
-    DISPLAYLEVEL(2, "\r%79s\r", "");   /* blank line */
-    DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
-        filesize, compressedfilesize, (double)compressedfilesize / filesize * 100);
-    {   double const seconds = (double)(clockEnd - clockStart) / CLOCKS_PER_SEC;
-        DISPLAYLEVEL(4,"Done in %.2f s ==> %.2f MiB/s\n", seconds,
-                        (double)filesize / seconds / 1024 / 1024);
-    }
-
-    /* Close & Free */
-    free(in_buff);
-    free(out_buff);
-    fclose(finput);
-    if (!LZ4IO_isStdout(output_filename)) fclose(foutput);  /* do not close stdout */
-
-    return 0;
+    TIME_t const timeStart = TIME_getTime();
+    clock_t const cpuStart = clock();
+    unsigned long long processed = 0;
+    int r = LZ4IO_compressLegacy_internal(&processed, input_filename, output_filename, compressionlevel, prefs);
+    LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
+    return r;
 }
 
 #define FNSPACE 30
@@ -500,6 +926,9 @@
                             const char* suffix,
                             int compressionLevel, const LZ4IO_prefs_t* prefs)
 {
+    TIME_t const timeStart = TIME_getTime();
+    clock_t const cpuStart = clock();
+    unsigned long long totalProcessed = 0;
     int i;
     int missed_files = 0;
     char* dstFileName = (char*)malloc(FNSPACE);
@@ -510,11 +939,13 @@
 
     /* loop on each file */
     for (i=0; i<ifntSize; i++) {
+        unsigned long long processed = 0;
         size_t const ifnSize = strlen(inFileNamesTable[i]);
         if (LZ4IO_isStdout(suffix)) {
-            missed_files += LZ4IO_compressFilename_Legacy(
+            missed_files += LZ4IO_compressLegacy_internal(&processed,
                                     inFileNamesTable[i], stdoutmark,
                                     compressionLevel, prefs);
+            totalProcessed += processed;
             continue;
         }
 
@@ -528,18 +959,19 @@
         strcpy(dstFileName, inFileNamesTable[i]);
         strcat(dstFileName, suffix);
 
-        missed_files += LZ4IO_compressFilename_Legacy(
+        missed_files += LZ4IO_compressLegacy_internal(&processed,
                                 inFileNamesTable[i], dstFileName,
                                 compressionLevel, prefs);
+        totalProcessed += processed;
     }
 
     /* Close & Free */
+    LZ4IO_finalTimeDisplay(timeStart, cpuStart, totalProcessed);
     free(dstFileName);
 
     return missed_files;
 }
 
-
 /*********************************************
 *  Compression using Frame format
 *********************************************/
@@ -549,25 +981,46 @@
     void*  dstBuffer;
     size_t dstBufferSize;
     LZ4F_compressionContext_t ctx;
+    LZ4F_preferences_t preparedPrefs;
     LZ4F_CDict* cdict;
+    TPool* tPool;
+    TPool* wPool; /* writer thread */
 } cRess_t;
 
-static void* LZ4IO_createDict(size_t* dictSize, const char* const dictFilename)
+static void LZ4IO_freeCResources(cRess_t ress)
+{
+    TPool_free(ress.tPool);
+    TPool_free(ress.wPool);
+
+    free(ress.srcBuffer);
+    free(ress.dstBuffer);
+
+    LZ4F_freeCDict(ress.cdict);
+    ress.cdict = NULL;
+
+    { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx);
+      if (LZ4F_isError(errorCode)) END_PROCESS(35, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); }
+}
+
+static void* LZ4IO_createDict(size_t* dictSize, const char* dictFilename)
 {
     size_t readSize;
     size_t dictEnd = 0;
     size_t dictLen = 0;
     size_t dictStart;
     size_t circularBufSize = LZ4_MAX_DICT_SIZE;
-    char*  circularBuf = (char*)malloc(circularBufSize);
-    char*  dictBuf;
+    char* circularBuf = (char*)malloc(circularBufSize);
+    char* dictBuf;
     FILE* dictFile;
 
-    if (!circularBuf) END_PROCESS(25, "Allocation error : not enough memory for circular buffer");
-    if (!dictFilename) END_PROCESS(26, "Dictionary error : no filename provided");
+    if (!dictFilename)
+        END_PROCESS(26, "Dictionary error : no filename provided");
+    if (!circularBuf)
+        END_PROCESS(25, "Allocation error : not enough memory for circular buffer");
 
     dictFile = LZ4IO_openSrcFile(dictFilename);
-    if (!dictFile) END_PROCESS(27, "Dictionary error : could not open dictionary file");
+    if (!dictFile)
+        END_PROCESS(27, "Dictionary error : could not open dictionary file");
 
     /* opportunistically seek to the part of the file we care about.
      * If this fails it's not a problem since we'll just read everything anyways. */
@@ -608,49 +1061,92 @@
     return dictBuf;
 }
 
-static LZ4F_CDict* LZ4IO_createCDict(const LZ4IO_prefs_t* const prefs)
+static LZ4F_CDict* LZ4IO_createCDict(const LZ4IO_prefs_t* io_prefs)
 {
     size_t dictionarySize;
     void* dictionaryBuffer;
     LZ4F_CDict* cdict;
-    if (!prefs->useDictionary) return NULL;
-    dictionaryBuffer = LZ4IO_createDict(&dictionarySize, prefs->dictionaryFilename);
+    if (!io_prefs->useDictionary) return NULL;
+    dictionaryBuffer = LZ4IO_createDict(&dictionarySize, io_prefs->dictionaryFilename);
     if (!dictionaryBuffer) END_PROCESS(29, "Dictionary error : could not create dictionary");
     cdict = LZ4F_createCDict(dictionaryBuffer, dictionarySize);
     free(dictionaryBuffer);
     return cdict;
 }
 
-static cRess_t LZ4IO_createCResources(const LZ4IO_prefs_t* const prefs)
+static cRess_t LZ4IO_createCResources(const LZ4IO_prefs_t* io_prefs)
 {
-    const size_t blockSize = prefs->blockSize;
+    const size_t chunkSize = 4 MB;
     cRess_t ress;
+    memset(&ress, 0, sizeof(ress));
 
-    LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION);
-    if (LZ4F_isError(errorCode)) END_PROCESS(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
+    /* set compression advanced parameters */
+    ress.preparedPrefs.autoFlush = 1;
+    ress.preparedPrefs.frameInfo.blockMode = (LZ4F_blockMode_t)io_prefs->blockIndependence;
+    ress.preparedPrefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)io_prefs->blockSizeId;
+    ress.preparedPrefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)io_prefs->blockChecksum;
+    ress.preparedPrefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)io_prefs->streamChecksum;
+    ress.preparedPrefs.favorDecSpeed = io_prefs->favorDecSpeed;
 
-    /* Allocate Memory */
-    ress.srcBuffer = malloc(blockSize);
-    ress.srcBufferSize = blockSize;
-    ress.dstBufferSize = LZ4F_compressFrameBound(blockSize, NULL);   /* cover worst case */
+    /* Allocate compression state */
+    {   LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION);
+        if (LZ4F_isError(errorCode))
+            END_PROCESS(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
+    }
+    assert(ress.ctx != NULL);
+
+    /* Allocate Buffers */
+    ress.srcBuffer = malloc(chunkSize);
+    ress.srcBufferSize = chunkSize;
+    ress.dstBufferSize = LZ4F_compressFrameBound(chunkSize, &ress.preparedPrefs);
     ress.dstBuffer = malloc(ress.dstBufferSize);
-    if (!ress.srcBuffer || !ress.dstBuffer) END_PROCESS(31, "Allocation error : not enough memory");
+    if (!ress.srcBuffer || !ress.dstBuffer)
+        END_PROCESS(31, "Allocation error : can't allocate buffers");
 
-    ress.cdict = LZ4IO_createCDict(prefs);
+    ress.cdict = LZ4IO_createCDict(io_prefs);
+
+    /* will be created it needed */
+    ress.tPool = NULL;
+    ress.wPool = NULL;
 
     return ress;
 }
 
-static void LZ4IO_freeCResources(cRess_t ress)
+typedef struct {
+    const LZ4F_preferences_t* prefs;
+    const LZ4F_CDict* cdict;
+} LZ4IO_CfcParameters;
+
+static size_t LZ4IO_compressFrameChunk(const void* params,
+                                    void* dst, size_t dstCapacity,
+                                    const void* src, size_t srcSize,
+                                    size_t prefixSize)
 {
-    free(ress.srcBuffer);
-    free(ress.dstBuffer);
+    const LZ4IO_CfcParameters* const cfcp = (const LZ4IO_CfcParameters*)params;
+    LZ4F_cctx* cctx = NULL;
+    {   LZ4F_errorCode_t const ccr = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
+        if (cctx==NULL || LZ4F_isError(ccr))
+            END_PROCESS(51, "unable to create a LZ4F compression context");
+    }
+    /* init state, and writes frame header, will be overwritten at next stage. */
+    if (prefixSize) {
+        size_t const whr = LZ4F_compressBegin_usingDict(cctx, dst, dstCapacity, (const char*)src - prefixSize, prefixSize, cfcp->prefs);
+        if (LZ4F_isError(whr))
+            END_PROCESS(52, "error initializing LZ4F compression context with prefix");
+        assert(prefixSize == 64 KB);
+    } else {
+        size_t const whr = LZ4F_compressBegin_usingCDict(cctx, dst, dstCapacity, cfcp->cdict, cfcp->prefs);
+        if (LZ4F_isError(whr))
+            END_PROCESS(53, "error initializing LZ4F compression context");
+    }
+    /* let's now compress, overwriting unused header */
+    {   size_t const cSize = LZ4F_compressUpdate(cctx, dst, dstCapacity, src, srcSize, NULL);
+        if (LZ4F_isError(cSize))
+            END_PROCESS(55, "error compressing with LZ4F_compressUpdate");
 
-    LZ4F_freeCDict(ress.cdict);
-    ress.cdict = NULL;
-
-    { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx);
-      if (LZ4F_isError(errorCode)) END_PROCESS(35, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); }
+        LZ4F_freeCompressionContext(cctx);
+        return (size_t) cSize;
+    }
 }
 
 /*
@@ -658,20 +1154,22 @@
  * result : 0 : compression completed correctly
  *          1 : missing or pb opening srcFileName
  */
-static int
-LZ4IO_compressFilename_extRess(cRess_t ress,
+int
+LZ4IO_compressFilename_extRess_MT(unsigned long long* inStreamSize,
+                               cRess_t* ress,
                                const char* srcFileName, const char* dstFileName,
-                               int compressionLevel, const LZ4IO_prefs_t* const io_prefs)
+                               int compressionLevel,
+                               const LZ4IO_prefs_t* const io_prefs)
 {
     unsigned long long filesize = 0;
     unsigned long long compressedfilesize = 0;
     FILE* dstFile;
-    void* const srcBuffer = ress.srcBuffer;
-    void* const dstBuffer = ress.dstBuffer;
-    const size_t dstBufferSize = ress.dstBufferSize;
-    const size_t blockSize = io_prefs->blockSize;
+    void* const srcBuffer = ress->srcBuffer;
+    void* const dstBuffer = ress->dstBuffer;
+    const size_t dstBufferSize = ress->dstBufferSize;
+    const size_t chunkSize = 4 MB;  /* each job should be "sufficiently large" */
     size_t readSize;
-    LZ4F_compressionContext_t ctx = ress.ctx;   /* just a pointer */
+    LZ4F_compressionContext_t ctx = ress->ctx;   /* just a pointer */
     LZ4F_preferences_t prefs;
 
     /* Init */
@@ -679,16 +1177,10 @@
     if (srcFile == NULL) return 1;
     dstFile = LZ4IO_openDstFile(dstFileName, io_prefs);
     if (dstFile == NULL) { fclose(srcFile); return 1; }
-    memset(&prefs, 0, sizeof(prefs));
 
-    /* Set compression parameters */
-    prefs.autoFlush = 1;
+    /* Adjust compression parameters */
+    prefs = ress->preparedPrefs;
     prefs.compressionLevel = compressionLevel;
-    prefs.frameInfo.blockMode = (LZ4F_blockMode_t)io_prefs->blockIndependence;
-    prefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)io_prefs->blockSizeId;
-    prefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)io_prefs->blockChecksum;
-    prefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)io_prefs->streamChecksum;
-    prefs.favorDecSpeed = io_prefs->favorDecSpeed;
     if (io_prefs->contentSizeFlag) {
       U64 const fileSize = UTIL_getOpenFileSize(srcFile);
       prefs.frameInfo.contentSize = fileSize;   /* == 0 if input == stdin */
@@ -696,20 +1188,22 @@
           DISPLAYLEVEL(3, "Warning : cannot determine input content size \n");
     }
 
-    /* read first block */
-    readSize  = fread(srcBuffer, (size_t)1, blockSize, srcFile);
-    if (ferror(srcFile)) END_PROCESS(40, "Error reading %s ", srcFileName);
+    /* read first chunk */
+    assert(chunkSize <= ress->srcBufferSize);
+    readSize  = fread(srcBuffer, (size_t)1, chunkSize, srcFile);
+    if (ferror(srcFile))
+        END_PROCESS(40, "Error reading first chunk (%u bytes) of '%s' ", (unsigned)chunkSize, srcFileName);
     filesize += readSize;
 
     /* single-block file */
-    if (readSize < blockSize) {
+    if (readSize < chunkSize) {
         /* Compress in single pass */
-        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress.cdict, &prefs);
+        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress->cdict, &prefs);
         if (LZ4F_isError(cSize))
             END_PROCESS(41, "Compression failed : %s", LZ4F_getErrorName(cSize));
         compressedfilesize = cSize;
         DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
-                      (unsigned)(filesize>>20), (double)compressedfilesize/(filesize+!filesize)*100);   /* avoid division by zero */
+                      (unsigned)(filesize>>20), (double)compressedfilesize/(double)(filesize+!filesize)*100);   /* avoid division by zero */
 
         /* Write Block */
         if (fwrite(dstBuffer, 1, cSize, dstFile) != cSize) {
@@ -719,41 +1213,121 @@
     else
 
     /* multiple-blocks file */
-    {
-        /* Write Frame Header */
-        size_t const headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress.cdict, &prefs);
-        if (LZ4F_isError(headerSize)) END_PROCESS(43, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
-        if (fwrite(dstBuffer, 1, headerSize, dstFile) != headerSize)
-            END_PROCESS(44, "Write error : cannot write header");
-        compressedfilesize += headerSize;
+    {   WriteRegister wr = WR_init(chunkSize);
+        void* prefixBuffer = NULL;
 
-        /* Main Loop - one block at a time */
-        while (readSize>0) {
-            size_t const outSize = LZ4F_compressUpdate(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, NULL);
-            if (LZ4F_isError(outSize))
-                END_PROCESS(45, "Compression failed : %s", LZ4F_getErrorName(outSize));
-            compressedfilesize += outSize;
-            DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
-                        (unsigned)(filesize>>20), (double)compressedfilesize/filesize*100);
+        int checksum = (int)prefs.frameInfo.contentChecksumFlag;
+        XXH32_state_t* xxh32 = NULL;
 
-            /* Write Block */
-            if (fwrite(dstBuffer, 1, outSize, dstFile) != outSize)
-                END_PROCESS(46, "Write error : cannot write compressed block");
+        LZ4IO_CfcParameters cfcp;
+        ReadTracker rjd;
 
-            /* Read next block */
-            readSize  = fread(srcBuffer, (size_t)1, (size_t)blockSize, srcFile);
-            filesize += readSize;
+        if (ress->tPool == NULL) {
+            ress->tPool = TPool_create(io_prefs->nbWorkers, 4);
+            assert(ress->wPool == NULL);
+            ress->wPool = TPool_create(1, 4);
+            if (ress->tPool == NULL || ress->wPool == NULL)
+                END_PROCESS(43, "can't create threadpools");
         }
-        if (ferror(srcFile)) END_PROCESS(47, "Error reading %s ", srcFileName);
+        cfcp.prefs = &prefs;
+        cfcp.cdict = ress->cdict;
+        rjd.tPool = ress->tPool;
+        rjd.wpool = ress->wPool;
+        rjd.fin = srcFile;
+        rjd.chunkSize = chunkSize;
+        rjd.totalReadSize = 0;
+        rjd.blockNb = 0;
+        rjd.xxh32 = xxh32;
+        rjd.compress = LZ4IO_compressFrameChunk;
+        rjd.compressParameters = &cfcp;
+        rjd.prefix = NULL;
+        rjd.fout = dstFile;
+        rjd.wr = &wr;
+        rjd.maxCBlockSize = LZ4F_compressFrameBound(chunkSize, &prefs);
+
+        /* process frame checksum externally */
+        if (checksum) {
+            xxh32 = XXH32_createState();
+            if (xxh32==NULL)
+                END_PROCESS(42, "could not init checksum");
+            XXH32_reset(xxh32, 0);
+            XXH32_update(xxh32, srcBuffer, readSize);
+            rjd.xxh32 = xxh32;
+        }
+
+        /* block dependency */
+        if (prefs.frameInfo.blockMode == LZ4F_blockLinked) {
+            prefixBuffer = malloc(64 KB);
+            if (prefixBuffer==NULL)
+                END_PROCESS(43, "cannot allocate small dictionary buffer");
+            rjd.prefix = prefixBuffer;
+        }
+
+        /* Write Frame Header */
+        /* note: simplification: do not employ dictionary when input size >= 4 MB,
+         * the benefit is very limited anyway, and is not worth the dependency cost */
+        {   size_t const headerSize = LZ4F_compressBegin(ctx, dstBuffer, dstBufferSize, &prefs);
+            if (LZ4F_isError(headerSize))
+                END_PROCESS(44, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
+            if (fwrite(dstBuffer, 1, headerSize, dstFile) != headerSize)
+                END_PROCESS(45, "Write error : cannot write header");
+            compressedfilesize = headerSize;
+        }
+        /* avoid duplicating effort to process content checksum (done externally) */
+        prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum;
+
+        /* process first block */
+        {   CompressJobDesc cjd;
+            cjd.wpool = ress->wPool;
+            cjd.buffer = srcBuffer;
+            cjd.prefixSize = 0;
+            cjd.inSize = readSize;
+            cjd.blockNb = 0;
+            cjd.compress = LZ4IO_compressFrameChunk;
+            cjd.compressParameters = &cfcp;
+            cjd.fout = dstFile;
+            cjd.wr = &wr;
+            cjd.maxCBlockSize = rjd.maxCBlockSize;
+            cjd.lastBlock = 0;
+            TPool_submitJob(ress->tPool, LZ4IO_compressChunk, &cjd);
+            rjd.totalReadSize = readSize;
+            rjd.blockNb = 1;
+            if (prefixBuffer) {
+                assert(readSize >= 64 KB);
+                memcpy(prefixBuffer, (char*)srcBuffer + readSize - 64 KB, 64 KB);
+            }
+
+            /* Start the job chain */
+            TPool_submitJob(ress->tPool, LZ4IO_readAndProcess, &rjd);
+
+            /* Wait for all completion */
+            TPool_jobsCompleted(ress->tPool);
+            TPool_jobsCompleted(ress->wPool);
+            compressedfilesize += wr.totalCSize;
+        }
 
         /* End of Frame mark */
-        {   size_t const endSize = LZ4F_compressEnd(ctx, dstBuffer, dstBufferSize, NULL);
-            if (LZ4F_isError(endSize))
-                END_PROCESS(48, "End of frame error : %s", LZ4F_getErrorName(endSize));
+        {   size_t endSize = 4;
+            assert(dstBufferSize >= 8);
+            memset(dstBuffer, 0, 4);
+            if (checksum) {
+                /* handle frame checksum externally
+                 * note: LZ4F_compressEnd already wrote a (bogus) checksum */
+                U32 const crc = XXH32_digest(xxh32);
+                LZ4IO_writeLE32( (char*)dstBuffer + 4, crc);
+                endSize = 8;
+            }
             if (fwrite(dstBuffer, 1, endSize, dstFile) != endSize)
                 END_PROCESS(49, "Write error : cannot write end of frame");
             compressedfilesize += endSize;
-    }   }
+            filesize = rjd.totalReadSize;
+        }
+
+        /* clean up*/
+        free(prefixBuffer);
+        XXH32_freeState(xxh32);
+        WR_destroy(&wr);
+    }
 
     /* Release file handlers */
     fclose (srcFile);
@@ -777,36 +1351,173 @@
     DISPLAYLEVEL(2, "\r%79s\r", "");
     DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
                     filesize, compressedfilesize,
-                    (double)compressedfilesize / (filesize + !filesize /* avoid division by zero */ ) * 100);
+                    (double)compressedfilesize / (double)(filesize + !filesize /* avoid division by zero */ ) * 100.);
+    *inStreamSize = filesize;
 
     return 0;
 }
 
+/*
+ * LZ4IO_compressFilename_extRess()
+ * result : 0 : compression completed correctly
+ *          1 : missing or pb opening srcFileName
+ */
+int
+LZ4IO_compressFilename_extRess_ST(unsigned long long* inStreamSize,
+                               const cRess_t* ress,
+                               const char* srcFileName, const char* dstFileName,
+                               int compressionLevel,
+                               const LZ4IO_prefs_t* const io_prefs)
+{
+    unsigned long long filesize = 0;
+    unsigned long long compressedfilesize = 0;
+    FILE* dstFile;
+    void* const srcBuffer = ress->srcBuffer;
+    void* const dstBuffer = ress->dstBuffer;
+    const size_t dstBufferSize = ress->dstBufferSize;
+    const size_t blockSize = io_prefs->blockSize;
+    size_t readSize;
+    LZ4F_compressionContext_t ctx = ress->ctx;   /* just a pointer */
+    LZ4F_preferences_t prefs;
+
+    /* Init */
+    FILE* const srcFile = LZ4IO_openSrcFile(srcFileName);
+    if (srcFile == NULL) return 1;
+    dstFile = LZ4IO_openDstFile(dstFileName, io_prefs);
+    if (dstFile == NULL) { fclose(srcFile); return 1; }
+    memset(&prefs, 0, sizeof(prefs));
+
+    /* Adjust compression parameters */
+    prefs = ress->preparedPrefs;
+    prefs.compressionLevel = compressionLevel;
+    if (io_prefs->contentSizeFlag) {
+      U64 const fileSize = UTIL_getOpenFileSize(srcFile);
+      prefs.frameInfo.contentSize = fileSize;   /* == 0 if input == stdin */
+      if (fileSize==0)
+          DISPLAYLEVEL(3, "Warning : cannot determine input content size \n");
+    }
+
+    /* read first block */
+    readSize  = fread(srcBuffer, (size_t)1, blockSize, srcFile);
+    if (ferror(srcFile)) END_PROCESS(40, "Error reading %s ", srcFileName);
+    filesize += readSize;
+
+    /* single-block file */
+    if (readSize < blockSize) {
+        /* Compress in single pass */
+        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress->cdict, &prefs);
+        if (LZ4F_isError(cSize))
+            END_PROCESS(41, "Compression failed : %s", LZ4F_getErrorName(cSize));
+        compressedfilesize = cSize;
+        DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
+                      (unsigned)(filesize>>20), (double)compressedfilesize/(double)(filesize+!filesize)*100);   /* avoid division by zero */
+
+        /* Write Block */
+        if (fwrite(dstBuffer, 1, cSize, dstFile) != cSize) {
+            END_PROCESS(42, "Write error : failed writing single-block compressed frame");
+    }   }
+
+    else
+
+    /* multiple-blocks file */
+    {
+        /* Write Frame Header */
+        size_t const headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress->cdict, &prefs);
+        if (LZ4F_isError(headerSize))
+            END_PROCESS(43, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
+        if (fwrite(dstBuffer, 1, headerSize, dstFile) != headerSize)
+            END_PROCESS(44, "Write error : cannot write header");
+        compressedfilesize += headerSize;
+
+        /* Main Loop - one block at a time */
+        while (readSize>0) {
+            size_t const outSize = LZ4F_compressUpdate(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, NULL);
+            if (LZ4F_isError(outSize))
+                END_PROCESS(45, "Compression failed : %s", LZ4F_getErrorName(outSize));
+            compressedfilesize += outSize;
+            DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
+                        (unsigned)(filesize>>20),
+                        (double)compressedfilesize / (double)filesize * 100.);
+
+            /* Write Block */
+            if (fwrite(dstBuffer, 1, outSize, dstFile) != outSize)
+                END_PROCESS(46, "Write error : cannot write compressed block");
+
+            /* Read next block */
+            readSize  = fread(srcBuffer, (size_t)1, (size_t)blockSize, srcFile);
+            filesize += readSize;
+        }
+        if (ferror(srcFile)) END_PROCESS(47, "Error reading %s ", srcFileName);
+
+        /* End of Frame mark */
+        {   size_t const endSize = LZ4F_compressEnd(ctx, dstBuffer, dstBufferSize, NULL);
+            if (LZ4F_isError(endSize))
+                END_PROCESS(48, "End of frame error : %s", LZ4F_getErrorName(endSize));
+            if (fwrite(dstBuffer, 1, endSize, dstFile) != endSize)
+                END_PROCESS(49, "Write error : cannot write end of frame");
+            compressedfilesize += endSize;
+        }
+    }
+
+    /* Release file handlers */
+    fclose (srcFile);
+    if (!LZ4IO_isStdout(dstFileName)) fclose(dstFile);  /* do not close stdout */
+
+    /* Copy owner, file permissions and modification time */
+    {   stat_t statbuf;
+        if (!LZ4IO_isStdin(srcFileName)
+         && !LZ4IO_isStdout(dstFileName)
+         && !LZ4IO_isDevNull(dstFileName)
+         && UTIL_getFileStat(srcFileName, &statbuf)) {
+            UTIL_setFileStat(dstFileName, &statbuf);
+    }   }
+
+    if (io_prefs->removeSrcFile) {  /* remove source file : --rm */
+        if (remove(srcFileName))
+            END_PROCESS(50, "Remove error : %s: %s", srcFileName, strerror(errno));
+    }
+
+    /* Final Status */
+    DISPLAYLEVEL(2, "\r%79s\r", "");
+    DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
+                    filesize, compressedfilesize,
+                    (double)compressedfilesize / (double)(filesize + !filesize /* avoid division by zero */ ) * 100.);
+    *inStreamSize = filesize;
+
+    return 0;
+}
+
+static int
+LZ4IO_compressFilename_extRess(unsigned long long* inStreamSize,
+                               cRess_t* ress,
+                               const char* srcFileName, const char* dstFileName,
+                               int compressionLevel,
+                               const LZ4IO_prefs_t* const io_prefs)
+{
+    if (LZ4IO_MULTITHREAD)
+        return LZ4IO_compressFilename_extRess_MT(inStreamSize, ress, srcFileName, dstFileName, compressionLevel, io_prefs);
+    /* Only single-thread available */
+    return LZ4IO_compressFilename_extRess_ST(inStreamSize, ress, srcFileName, dstFileName, compressionLevel, io_prefs);
+}
 
 int LZ4IO_compressFilename(const char* srcFileName, const char* dstFileName, int compressionLevel, const LZ4IO_prefs_t* prefs)
 {
-    UTIL_time_t const timeStart = UTIL_getTime();
+    TIME_t const timeStart = TIME_getTime();
     clock_t const cpuStart = clock();
-    cRess_t const ress = LZ4IO_createCResources(prefs);
+    cRess_t ress = LZ4IO_createCResources(prefs);
+    unsigned long long processed;
 
-    int const result = LZ4IO_compressFilename_extRess(ress, srcFileName, dstFileName, compressionLevel, prefs);
+    int const result = LZ4IO_compressFilename_extRess(&processed, &ress, srcFileName, dstFileName, compressionLevel, prefs);
 
     /* Free resources */
     LZ4IO_freeCResources(ress);
 
     /* Final Status */
-    {   clock_t const cpuEnd = clock();
-        double const cpuLoad_s = (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC;
-        U64 const timeLength_ns = UTIL_clockSpanNano(timeStart);
-        double const timeLength_s = (double)timeLength_ns / 1000000000;
-        DISPLAYLEVEL(4, "Completed in %.2f sec  (cpu load : %.0f%%)\n",
-                        timeLength_s, (cpuLoad_s / timeLength_s) * 100);
-    }
+    LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
 
     return result;
 }
 
-
 int LZ4IO_compressMultipleFilenames(
                               const char** inFileNamesTable, int ifntSize,
                               const char* suffix,
@@ -819,17 +1530,22 @@
     size_t ofnSize = FNSPACE;
     const size_t suffixSize = strlen(suffix);
     cRess_t ress;
+    unsigned long long totalProcessed = 0;
+    TIME_t timeStart = TIME_getTime();
+    clock_t cpuStart = clock();
 
     if (dstFileName == NULL) return ifntSize;   /* not enough memory */
     ress = LZ4IO_createCResources(prefs);
 
     /* loop on each file */
     for (i=0; i<ifntSize; i++) {
+        unsigned long long processed;
         size_t const ifnSize = strlen(inFileNamesTable[i]);
         if (LZ4IO_isStdout(suffix)) {
-            missed_files += LZ4IO_compressFilename_extRess(ress,
+            missed_files += LZ4IO_compressFilename_extRess(&processed, &ress,
                                     inFileNamesTable[i], stdoutmark,
                                     compressionLevel, prefs);
+            totalProcessed += processed;
             continue;
         }
         /* suffix != stdout => compress into a file => generate its name */
@@ -844,14 +1560,16 @@
         strcpy(dstFileName, inFileNamesTable[i]);
         strcat(dstFileName, suffix);
 
-        missed_files += LZ4IO_compressFilename_extRess(ress,
+        missed_files += LZ4IO_compressFilename_extRess(&processed, &ress,
                                 inFileNamesTable[i], dstFileName,
                                 compressionLevel, prefs);
+        totalProcessed += processed;
     }
 
     /* Close & Free */
     LZ4IO_freeCResources(ress);
     free(dstFileName);
+    LZ4IO_finalTimeDisplay(timeStart, cpuStart, totalProcessed);
 
     return missed_files;
 }
@@ -861,10 +1579,10 @@
 /* ********************** LZ4 file-stream Decompression **************** */
 /* ********************************************************************* */
 
-/* It's presumed that s points to a memory space of size >= 4 */
-static unsigned LZ4IO_readLE32 (const void* s)
+/* It's presumed that @p points to a memory space of size >= 4 */
+static unsigned LZ4IO_readLE32 (const void* p)
 {
-    const unsigned char* const srcPtr = (const unsigned char*)s;
+    const unsigned char* const srcPtr = (const unsigned char*)p;
     unsigned value32 = srcPtr[0];
     value32 += (unsigned)srcPtr[1] <<  8;
     value32 += (unsigned)srcPtr[2] << 16;
@@ -949,7 +1667,7 @@
     if (storedSkips>0) {   /* implies sparseFileSupport>0 */
         const char lastZeroByte[1] = { 0 };
         if (UTIL_fseek(file, storedSkips-1, SEEK_CUR) != 0)
-            END_PROCESS(68, "Final skip error (sparse file)\n");
+            END_PROCESS(69, "Final skip error (sparse file)\n");
         if (fwrite(lastZeroByte, 1, 1, file) != 1)
             END_PROCESS(69, "Write error : cannot write last zero\n");
     }
@@ -958,6 +1676,152 @@
 
 static unsigned g_magicRead = 0;   /* out-parameter of LZ4IO_decodeLegacyStream() */
 
+#if LZ4IO_MULTITHREAD
+
+typedef struct {
+    void* buffer;
+    size_t size;
+    FILE* f;
+    int sparseEnable;
+    unsigned* storedSkips;
+    const unsigned long long* totalSize;
+} ChunkToWrite;
+
+static void LZ4IO_writeDecodedChunk(void* arg)
+{
+    ChunkToWrite* const ctw = (ChunkToWrite*)arg;
+    assert(ctw != NULL);
+
+    /* note: works because only 1 thread */
+    *ctw->storedSkips = LZ4IO_fwriteSparse(ctw->f, ctw->buffer, ctw->size, ctw->sparseEnable, *ctw->storedSkips); /* success or die */
+    DISPLAYUPDATE(2, "\rDecompressed : %u MiB  ", (unsigned)(ctw->totalSize[0] >>20));
+
+    /* clean up */
+    free(ctw);
+}
+
+typedef struct {
+    void* inBuffer;
+    size_t inSize;
+    void* outBuffer;
+    unsigned long long* totalSize;
+    TPool* wPool;
+    FILE* foutput;
+    int sparseEnable;
+    unsigned* storedSkips;
+} LegacyBlockInput;
+
+static void LZ4IO_decompressBlockLegacy(void* arg)
+{
+    int decodedSize;
+    LegacyBlockInput* const lbi = (LegacyBlockInput*)arg;
+
+    decodedSize = LZ4_decompress_safe((const char*)lbi->inBuffer, (char*)lbi->outBuffer, (int)lbi->inSize, LEGACY_BLOCKSIZE);
+    if (decodedSize < 0) END_PROCESS(64, "Decoding Failed ! Corrupted input detected !");
+    *lbi->totalSize += (unsigned long long)decodedSize; /* note: works because only 1 thread */
+
+    /* push to write thread */
+    {   ChunkToWrite* const ctw = (ChunkToWrite*)malloc(sizeof(*ctw));
+        if (ctw==NULL) {
+            END_PROCESS(33, "Allocation error : can't describe new write job");
+        }
+        ctw->buffer = lbi->outBuffer;
+        ctw->size = (size_t)decodedSize;
+        ctw->f = lbi->foutput;
+        ctw->sparseEnable = lbi->sparseEnable;
+        ctw->storedSkips = lbi->storedSkips;
+        ctw->totalSize = lbi->totalSize;
+        TPool_submitJob(lbi->wPool, LZ4IO_writeDecodedChunk, ctw);
+    }
+
+    /* clean up */
+    free(lbi);
+}
+
+static unsigned long long
+LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput, const LZ4IO_prefs_t* prefs)
+{
+    unsigned long long streamSize = 0;
+    unsigned storedSkips = 0;
+
+    TPool* const tPool = TPool_create(1, 1);
+    TPool* const wPool = TPool_create(1, 1);
+#define NB_BUFFSETS 4 /* 1 being read, 1 being processed, 1 being written, 1 being queued */
+    void* inBuffs[NB_BUFFSETS];
+    void* outBuffs[NB_BUFFSETS];
+    int bSetNb;
+
+    if (tPool == NULL || wPool == NULL)
+        END_PROCESS(21, "threadpool creation error ");
+
+    /* allocate buffers up front */
+    for (bSetNb=0; bSetNb<NB_BUFFSETS; bSetNb++) {
+        inBuffs[bSetNb] = malloc((size_t)LZ4_compressBound(LEGACY_BLOCKSIZE));
+        outBuffs[bSetNb] = malloc(LEGACY_BLOCKSIZE);
+        if (!inBuffs[bSetNb] || !outBuffs[bSetNb])
+            END_PROCESS(31, "Allocation error : can't allocate buffer for legacy decoding");
+    }
+
+    /* Main Loop */
+    for (bSetNb = 0;;bSetNb = (bSetNb+1) % NB_BUFFSETS) {
+        char header[LZ4IO_LEGACY_BLOCK_HEADER_SIZE];
+        unsigned int blockSize;
+
+        /* Block Size */
+        {   size_t const sizeCheck = fread(header, 1, LZ4IO_LEGACY_BLOCK_HEADER_SIZE, finput);
+            if (sizeCheck == 0) break;                   /* Nothing to read : file read is completed */
+            if (sizeCheck != LZ4IO_LEGACY_BLOCK_HEADER_SIZE)
+                END_PROCESS(61, "Error: cannot read block size in Legacy format");
+        }
+        blockSize = LZ4IO_readLE32(header);       /* Convert to Little Endian */
+        if (blockSize > LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) {
+            /* Cannot read next block : maybe new stream ? */
+            g_magicRead = blockSize;
+            break;
+        }
+
+        /* Read Block */
+        {   size_t const sizeCheck = fread(inBuffs[bSetNb], 1, blockSize, finput);
+            if (sizeCheck != blockSize)
+                END_PROCESS(63, "Read error : cannot access compressed block !");
+            /* push to decoding thread */
+            {   LegacyBlockInput* const lbi = (LegacyBlockInput*)malloc(sizeof(*lbi));
+                if (lbi==NULL)
+                    END_PROCESS(64, "Allocation error : not enough memory to allocate job descriptor");
+                lbi->inBuffer = inBuffs[bSetNb];
+                lbi->inSize = blockSize;
+                lbi->outBuffer = outBuffs[bSetNb];
+                lbi->wPool = wPool;
+                lbi->totalSize = &streamSize;
+                lbi->foutput = foutput;
+                lbi->sparseEnable = prefs->sparseFileSupport;
+                lbi->storedSkips = &storedSkips;
+                TPool_submitJob(tPool, LZ4IO_decompressBlockLegacy, lbi);
+            }
+        }
+    }
+    if (ferror(finput)) END_PROCESS(65, "Read error : ferror");
+
+    /* Wait for all completion */
+    TPool_jobsCompleted(tPool);
+    TPool_jobsCompleted(wPool);
+
+    /* flush last zeroes */
+    LZ4IO_fwriteSparseEnd(foutput, storedSkips);
+
+    /* Free */
+    TPool_free(wPool);
+    TPool_free(tPool);
+    for (bSetNb=0; bSetNb<NB_BUFFSETS; bSetNb++) {
+        free(inBuffs[bSetNb]);
+        free(outBuffs[bSetNb]);
+    }
+
+    return streamSize;
+}
+
+#else
+
 static unsigned long long
 LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput, const LZ4IO_prefs_t* prefs)
 {
@@ -967,7 +1831,7 @@
     /* Allocate Memory */
     char* const in_buff  = (char*)malloc((size_t)LZ4_compressBound(LEGACY_BLOCKSIZE));
     char* const out_buff = (char*)malloc(LEGACY_BLOCKSIZE);
-    if (!in_buff || !out_buff) END_PROCESS(51, "Allocation error : not enough memory");
+    if (!in_buff || !out_buff) END_PROCESS(61, "Allocation error : not enough memory");
 
     /* Main Loop */
     while (1) {
@@ -976,7 +1840,8 @@
         /* Block Size */
         {   size_t const sizeCheck = fread(in_buff, 1, LZ4IO_LEGACY_BLOCK_HEADER_SIZE, finput);
             if (sizeCheck == 0) break;                   /* Nothing to read : file read is completed */
-            if (sizeCheck != LZ4IO_LEGACY_BLOCK_HEADER_SIZE) END_PROCESS(52, "Read error : cannot access block size ");
+            if (sizeCheck != LZ4IO_LEGACY_BLOCK_HEADER_SIZE)
+                END_PROCESS(62, "Error: cannot read block size in Legacy format");
         }
         blockSize = LZ4IO_readLE32(in_buff);       /* Convert to Little Endian */
         if (blockSize > LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) {
@@ -987,16 +1852,16 @@
 
         /* Read Block */
         { size_t const sizeCheck = fread(in_buff, 1, blockSize, finput);
-          if (sizeCheck != blockSize) END_PROCESS(53, "Read error : cannot access compressed block !"); }
+          if (sizeCheck != blockSize) END_PROCESS(63, "Read error : cannot access compressed block !"); }
 
         /* Decode Block */
         {   int const decodeSize = LZ4_decompress_safe(in_buff, out_buff, (int)blockSize, LEGACY_BLOCKSIZE);
-            if (decodeSize < 0) END_PROCESS(54, "Decoding Failed ! Corrupted input detected !");
+            if (decodeSize < 0) END_PROCESS(64, "Decoding Failed ! Corrupted input detected !");
             streamSize += (unsigned long long)decodeSize;
             /* Write Block */
             storedSkips = LZ4IO_fwriteSparse(foutput, out_buff, (size_t)decodeSize, prefs->sparseFileSupport, storedSkips); /* success or die */
     }   }
-    if (ferror(finput)) END_PROCESS(55, "Read error : ferror");
+    if (ferror(finput)) END_PROCESS(65, "Read error : ferror");
 
     LZ4IO_fwriteSparseEnd(foutput, storedSkips);
 
@@ -1006,7 +1871,7 @@
 
     return streamSize;
 }
-
+#endif
 
 
 typedef struct {
@@ -1064,6 +1929,271 @@
 }
 
 
+#if LZ4IO_MULTITHREAD
+
+#define INBUFF_SIZE (4 MB)
+#define OUTBUFF_SIZE (1 * INBUFF_SIZE)
+#define OUTBUFF_QUEUE 1
+#define PBUFFERS_NB (1 /* being decompressed */ + OUTBUFF_QUEUE + 1 /* being written to io */)
+
+typedef struct {
+    void* ptr;
+    size_t capacity;
+    size_t size;
+} Buffer;
+
+/* BufferPool:
+ * Based on ayncio property :
+ * all buffers are allocated and released in order,
+ * maximum nb of buffers limited by queues */
+
+typedef struct {
+    Buffer buffers[PBUFFERS_NB];
+    int availNext;
+    int usedIdx;
+} BufferPool;
+
+static void LZ4IO_freeBufferPool(BufferPool* bp)
+{
+    int i;
+    if (bp==NULL) return;
+    for (i=0; i<PBUFFERS_NB; i++)
+        free(bp->buffers[i].ptr);
+    free(bp);
+}
+
+static BufferPool* LZ4IO_createBufferPool(size_t bufSize)
+{
+    BufferPool* const bp = (BufferPool*)calloc(1, sizeof(*bp));
+    int i;
+    if (bp==NULL) return NULL;
+    for (i=0; i<PBUFFERS_NB; i++) {
+        bp->buffers[i].ptr = malloc(bufSize);
+        if (bp->buffers[i].ptr == NULL) {
+            LZ4IO_freeBufferPool(bp);
+            return NULL;
+        }
+         bp->buffers[i].capacity = bufSize;
+         bp->buffers[i].size = 0;
+    }
+    bp->availNext = 0;
+    bp->usedIdx = 0;
+    return bp;
+}
+
+/* Note: Thread Sanitizer can be detected with below macro
+ * but it's not guaranteed (doesn't seem to work with clang) */
+#ifdef __SANITIZE_THREAD__
+# undef LZ4IO_NO_TSAN_ONLY
+#endif
+
+static Buffer BufPool_getBuffer(BufferPool* bp)
+{
+    assert(bp != NULL);
+#ifdef LZ4IO_NO_TSAN_ONLY
+    /* The following assert() are susceptible to race conditions */
+    assert(bp->availNext >= bp->usedIdx);
+    assert(bp->availNext < bp->usedIdx + PBUFFERS_NB);
+#endif
+    {   int id = bp->availNext++ % PBUFFERS_NB;
+        assert(bp->buffers[id].size == 0);
+        return bp->buffers[id];
+}   }
+
+void BufPool_releaseBuffer(BufferPool* bp, Buffer buf)
+{
+    assert(bp != NULL);
+#ifdef LZ4IO_NO_TSAN_ONLY
+    /* The following assert() is susceptible to race conditions */
+    assert(bp->usedIdx < bp->availNext);
+#endif
+    {   int id = bp->usedIdx++ % PBUFFERS_NB;
+        assert(bp->buffers[id].ptr == buf.ptr);
+        bp->buffers[id].size = 0;
+}   }
+
+typedef struct {
+    Buffer bufOut;
+    FILE* fOut;
+    BufferPool* bp;
+    int sparseEnable;
+    unsigned* storedSkips;
+    unsigned long long* totalSize;
+} LZ4FChunkToWrite;
+
+static void LZ4IO_writeDecodedLZ4FChunk(void* arg)
+{
+    LZ4FChunkToWrite* const ctw = (LZ4FChunkToWrite*)arg;
+    assert(ctw != NULL);
+
+    /* note: works because only 1 thread */
+    *ctw->storedSkips = LZ4IO_fwriteSparse(ctw->fOut, ctw->bufOut.ptr, ctw->bufOut.size, ctw->sparseEnable, *ctw->storedSkips); /* success or die */
+    *ctw->totalSize += (unsigned long long)ctw->bufOut.size; /* note: works because only 1 thread */
+    DISPLAYUPDATE(2, "\rDecompressed : %u MiB  ", (unsigned)(ctw->totalSize[0] >> 20));
+
+    /* clean up */
+    BufPool_releaseBuffer(ctw->bp, ctw->bufOut);
+    free(ctw);
+}
+
+typedef struct {
+    LZ4F_dctx* dctx;
+    const void* inBuffer;
+    size_t inSize;
+    const void* dictBuffer;
+    size_t dictBufferSize;
+    BufferPool* bp;
+    unsigned long long* totalSize;
+    LZ4F_errorCode_t* lastStatus;
+    TPool* wPool;
+    FILE* foutput;
+    int sparseEnable;
+    unsigned* storedSkips;
+} LZ4FChunk;
+
+static void LZ4IO_decompressLZ4FChunk(void* arg)
+{
+    LZ4FChunk* const lz4fc = (LZ4FChunk*)arg;
+    const char* inPtr = (const char*)lz4fc->inBuffer;
+    size_t pos = 0;
+
+    while ((pos < lz4fc->inSize)) {  /* still to read */
+        size_t remainingInSize = lz4fc->inSize - pos;
+        Buffer b = BufPool_getBuffer(lz4fc->bp);
+        if (b.capacity != OUTBUFF_SIZE)
+            END_PROCESS(33, "Could not allocate output buffer!");
+        assert(b.size == 0);
+        b.size = b.capacity;
+        {   size_t nextToLoad = LZ4F_decompress_usingDict(lz4fc->dctx,
+                                b.ptr, &b.size,
+                                inPtr + pos, &remainingInSize,
+                                lz4fc->dictBuffer, lz4fc->dictBufferSize,
+                                NULL);
+            if (LZ4F_isError(nextToLoad))
+                END_PROCESS(34, "Decompression error : %s", LZ4F_getErrorName(nextToLoad));
+            *lz4fc->lastStatus = nextToLoad;
+        }
+        assert(remainingInSize <= lz4fc->inSize - pos);
+        pos += remainingInSize;
+        assert(b.size <= b.capacity);
+
+        /* push to write thread */
+        {   LZ4FChunkToWrite* const ctw = (LZ4FChunkToWrite*)malloc(sizeof(*ctw));
+            if (ctw==NULL) {
+                END_PROCESS(35, "Allocation error : can't describe new write job");
+            }
+            ctw->bufOut = b;
+            ctw->fOut = lz4fc->foutput;
+            ctw->bp = lz4fc->bp;
+            ctw->sparseEnable = lz4fc->sparseEnable;
+            ctw->storedSkips = lz4fc->storedSkips;
+            ctw->totalSize = lz4fc->totalSize;
+            TPool_submitJob(lz4fc->wPool, LZ4IO_writeDecodedLZ4FChunk, ctw);
+        }
+    }
+
+    /* clean up */
+    free(lz4fc);
+}
+
+static unsigned long long
+LZ4IO_decompressLZ4F(dRess_t ress,
+                     FILE* const srcFile, FILE* const dstFile,
+                     const LZ4IO_prefs_t* const prefs)
+{
+    unsigned long long filesize = 0;
+    LZ4F_errorCode_t nextToLoad;
+    LZ4F_errorCode_t lastStatus = 1;
+    unsigned storedSkips = 0;
+    LZ4F_decompressOptions_t const dOpt_skipCrc = { 0, 1, 0, 0 };
+    const LZ4F_decompressOptions_t* const dOptPtr =
+        ((prefs->blockChecksum==0) && (prefs->streamChecksum==0)) ?
+        &dOpt_skipCrc : NULL;
+    TPool* const tPool = TPool_create(1, 1);
+    TPool* const wPool = TPool_create(1, 1);
+    BufferPool* const bp = LZ4IO_createBufferPool(OUTBUFF_SIZE);
+#define NB_BUFFSETS 4 /* 1 being read, 1 being processed, 1 being written, 1 being queued */
+    void* inBuffs[NB_BUFFSETS];
+    int bSetNb;
+
+    /* checks */
+    if (tPool == NULL || wPool == NULL || bp==NULL)
+        END_PROCESS(22, "threadpool creation error ");
+
+    /* allocate buffers up front */
+    for (bSetNb=0; bSetNb<NB_BUFFSETS; bSetNb++) {
+        inBuffs[bSetNb] = malloc((size_t)INBUFF_SIZE);
+        if (!inBuffs[bSetNb])
+            END_PROCESS(23, "Allocation error : can't allocate buffer for legacy decoding");
+    }
+
+    /* Init feed with magic number (already consumed from FILE* sFile) */
+    {   size_t inSize = MAGICNUMBER_SIZE;
+        size_t outSize= 0;
+        LZ4IO_writeLE32(ress.srcBuffer, LZ4IO_MAGICNUMBER);
+        nextToLoad = LZ4F_decompress_usingDict(ress.dCtx,
+                            ress.dstBuffer, &outSize,
+                            ress.srcBuffer, &inSize,
+                            ress.dictBuffer, ress.dictBufferSize,
+                            dOptPtr);  /* set it once, it's enough */
+        if (LZ4F_isError(nextToLoad))
+            END_PROCESS(23, "Header error : %s", LZ4F_getErrorName(nextToLoad));
+    }
+
+    /* Main Loop */
+    assert(nextToLoad);
+    for (bSetNb = 0; ; bSetNb = (bSetNb+1) % NB_BUFFSETS) {
+        size_t readSize;
+
+        /* Read input */
+        readSize = fread(inBuffs[bSetNb], 1, INBUFF_SIZE, srcFile);
+        if (ferror(srcFile)) END_PROCESS(26, "Read error");
+
+        /* push to decoding thread */
+        {   LZ4FChunk* const lbi = (LZ4FChunk*)malloc(sizeof(*lbi));
+            if (lbi==NULL)
+                END_PROCESS(25, "Allocation error : not enough memory to allocate job descriptor");
+            lbi->dctx = ress.dCtx;
+            lbi->inBuffer = inBuffs[bSetNb];
+            lbi->inSize = readSize;
+            lbi->dictBuffer = ress.dictBuffer;
+            lbi->dictBufferSize = ress.dictBufferSize;
+            lbi->bp = bp;
+            lbi->wPool = wPool;
+            lbi->totalSize = &filesize;
+            lbi->lastStatus = &lastStatus;
+            lbi->foutput = dstFile;
+            lbi->sparseEnable = prefs->sparseFileSupport;
+            lbi->storedSkips = &storedSkips;
+            TPool_submitJob(tPool, LZ4IO_decompressLZ4FChunk, lbi);
+        }
+        if (readSize < INBUFF_SIZE) break;   /* likely reached end of stream */
+    }
+    assert(feof(srcFile));
+
+    /* Wait for all decompression completion */
+    TPool_jobsCompleted(tPool);
+
+    /* flush */
+    if (lastStatus != 0) {
+        END_PROCESS(26, "LZ4F frame decoding could not complete: invalid frame");
+    }
+    TPool_jobsCompleted(wPool);
+    if (!prefs->testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips);
+
+    /* Clean */
+    for (bSetNb=0; bSetNb<NB_BUFFSETS; bSetNb++) {
+        free(inBuffs[bSetNb]);
+    }
+    LZ4IO_freeBufferPool(bp);
+    TPool_free(wPool);
+    TPool_free(tPool);
+
+    return filesize;
+}
+
+#else
+
 static unsigned long long
 LZ4IO_decompressLZ4F(dRess_t ress,
                      FILE* const srcFile, FILE* const dstFile,
@@ -1129,11 +2259,13 @@
     if (ferror(srcFile)) END_PROCESS(67, "Read error");
 
     if (!prefs->testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips);
-    if (nextToLoad!=0) END_PROCESS(68, "Unfinished stream");
+    if (nextToLoad!=0)
+        END_PROCESS(68, "Unfinished stream (nextToLoad=%u)", (unsigned)nextToLoad);
 
     return filesize;
 }
 
+#endif /* LZ4IO_MULTITHREAD */
 
 /* LZ4IO_passThrough:
  * just output the same content as input, no decoding.
@@ -1170,7 +2302,6 @@
  * read and forget from input.
 **/
 #define SKIP_BUFF_SIZE (16 KB)
-#define MIN(a,b)   ( ((a)<(b)) ? (a) : (b) )
 static int skipStream(FILE* f, unsigned offset)
 {
     char buf[SKIP_BUFF_SIZE];
@@ -1271,7 +2402,8 @@
 
 
 static int
-LZ4IO_decompressSrcFile(dRess_t ress,
+LZ4IO_decompressSrcFile(unsigned long long* outGenSize,
+                        dRess_t ress,
                         const char* input_filename, const char* output_filename,
                         const LZ4IO_prefs_t* const prefs)
 {
@@ -1302,7 +2434,8 @@
 
     /* Final Status */
     DISPLAYLEVEL(2, "\r%79s\r", "");
-    DISPLAYLEVEL(2, "%-20.20s : decoded %llu bytes \n", input_filename, filesize);
+    DISPLAYLEVEL(2, "%-30.30s : decoded %llu bytes \n", input_filename, filesize);
+    *outGenSize = filesize;
     (void)output_filename;
 
     return result;
@@ -1310,8 +2443,10 @@
 
 
 static int
-LZ4IO_decompressDstFile(dRess_t ress,
-                        const char* input_filename, const char* output_filename,
+LZ4IO_decompressDstFile(unsigned long long* outGenSize,
+                        dRess_t ress,
+                        const char* input_filename,
+                        const char* output_filename,
                         const LZ4IO_prefs_t* const prefs)
 {
     int result;
@@ -1325,7 +2460,7 @@
         stat_result = 1;
 
     ress.dstFile = foutput;
-    result = LZ4IO_decompressSrcFile(ress, input_filename, output_filename, prefs);
+    result = LZ4IO_decompressSrcFile(outGenSize, ress, input_filename, output_filename, prefs);
 
     fclose(foutput);
 
@@ -1348,16 +2483,15 @@
 int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename, const LZ4IO_prefs_t* prefs)
 {
     dRess_t const ress = LZ4IO_createDResources(prefs);
-    clock_t const start = clock();
+    TIME_t const timeStart = TIME_getTime();
+    clock_t const cpuStart = clock();
+    unsigned long long processed = 0;
 
-    int const status = LZ4IO_decompressDstFile(ress, input_filename, output_filename, prefs);
-
-    clock_t const end = clock();
-    double const seconds = (double)(end - start) / CLOCKS_PER_SEC;
-    DISPLAYLEVEL(4, "Done in %.2f sec  \n", seconds);
-
+    int const errStat = LZ4IO_decompressDstFile(&processed, ress, input_filename, output_filename, prefs);
+    if (errStat)
+        LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
     LZ4IO_freeDResources(ress);
-    return status;
+    return errStat;
 }
 
 
@@ -1367,12 +2501,15 @@
                             const LZ4IO_prefs_t* prefs)
 {
     int i;
+    unsigned long long totalProcessed = 0;
     int skippedFiles = 0;
     int missingFiles = 0;
     char* outFileName = (char*)malloc(FNSPACE);
     size_t ofnSize = FNSPACE;
     size_t const suffixSize = strlen(suffix);
     dRess_t ress = LZ4IO_createDResources(prefs);
+    TIME_t timeStart = TIME_getTime();
+    clock_t cpuStart = clock();
 
     if (outFileName==NULL) END_PROCESS(70, "Memory allocation error");
     if (prefs->blockChecksum==0 && prefs->streamChecksum==0) {
@@ -1381,10 +2518,12 @@
     ress.dstFile = LZ4IO_openDstFile(stdoutmark, prefs);
 
     for (i=0; i<ifntSize; i++) {
+        unsigned long long processed = 0;
         size_t const ifnSize = strlen(inFileNamesTable[i]);
         const char* const suffixPtr = inFileNamesTable[i] + ifnSize - suffixSize;
         if (LZ4IO_isStdout(suffix) || LZ4IO_isDevNull(suffix)) {
-            missingFiles += LZ4IO_decompressSrcFile(ress, inFileNamesTable[i], suffix, prefs);
+            missingFiles += LZ4IO_decompressSrcFile(&processed, ress, inFileNamesTable[i], suffix, prefs);
+            totalProcessed += processed;
             continue;
         }
         if (ofnSize <= ifnSize-suffixSize+1) {
@@ -1400,11 +2539,13 @@
         }
         memcpy(outFileName, inFileNamesTable[i], ifnSize - suffixSize);
         outFileName[ifnSize-suffixSize] = '\0';
-        missingFiles += LZ4IO_decompressDstFile(ress, inFileNamesTable[i], outFileName, prefs);
+        missingFiles += LZ4IO_decompressDstFile(&processed, ress, inFileNamesTable[i], outFileName, prefs);
+        totalProcessed += processed;
     }
 
     LZ4IO_freeDResources(ress);
     free(outFileName);
+    LZ4IO_finalTimeDisplay(timeStart, cpuStart, totalProcessed);
     return missingFiles + skippedFiles;
 }
 
@@ -1542,7 +2683,7 @@
 }
 
 /* buffer : must be valid memory area of at least 10 bytes */
-static const char* LZ4IO_toHuman(long double size, char *buf)
+static const char* LZ4IO_toHuman(long double size, char* buf)
 {
     const char units[] = {"\0KMGTPEZY"};
     size_t i = 0;
@@ -1566,7 +2707,7 @@
  *  + report nb of blocks, hence max. possible decompressed size (when not reported in header)
  */
 static LZ4IO_infoResult
-LZ4IO_getCompressedFileInfo(LZ4IO_cFileInfo_t* cfinfo, const char* input_filename)
+LZ4IO_getCompressedFileInfo(LZ4IO_cFileInfo_t* cfinfo, const char* input_filename, int displayNow)
 {
     LZ4IO_infoResult result = LZ4IO_format_not_known;  /* default result (error) */
     unsigned char buffer[LZ4F_HEADER_SIZE_MAX];
@@ -1619,23 +2760,22 @@
                             if (totalBlocksSize) {
                                 char bTypeBuffer[5];
                                 LZ4IO_blockTypeID(frameInfo.lz4FrameInfo.blockSizeID, frameInfo.lz4FrameInfo.blockMode, bTypeBuffer);
-                                DISPLAYLEVEL(3, "    %6llu %14s %5s %8s",
+                                if (displayNow) DISPLAYOUT("    %6llu %14s %5s %8s",
                                              cfinfo->frameCount + 1,
                                              LZ4IO_frameTypeNames[frameInfo.frameType],
                                              bTypeBuffer,
                                              frameInfo.lz4FrameInfo.contentChecksumFlag ? "XXH32" : "-");
                                 if (frameInfo.lz4FrameInfo.contentSize) {
-                                    {   double const ratio = (double)(totalBlocksSize + hSize) / frameInfo.lz4FrameInfo.contentSize * 100;
-                                        DISPLAYLEVEL(3, " %20llu %20llu %9.2f%%\n",
-                                                     totalBlocksSize + hSize,
-                                                     frameInfo.lz4FrameInfo.contentSize,
-                                                     ratio);
-                                    }
+                                    double const ratio = (double)(totalBlocksSize + hSize) / (double)frameInfo.lz4FrameInfo.contentSize * 100;
+                                    if (displayNow) DISPLAYOUT(" %20llu %20llu %9.2f%%\n",
+                                                    totalBlocksSize + hSize,
+                                                    frameInfo.lz4FrameInfo.contentSize,
+                                                    ratio);
                                     /* Now we've consumed frameInfo we can use it to store the total contentSize */
                                     frameInfo.lz4FrameInfo.contentSize += cfinfo->frameSummary.lz4FrameInfo.contentSize;
                                 }
                                 else {
-                                    DISPLAYLEVEL(3, " %20llu %20s %9s \n", totalBlocksSize + hSize, "-", "-");
+                                    if (displayNow) DISPLAYOUT(" %20llu %20s %9s \n", totalBlocksSize + hSize, "-", "-");
                                     cfinfo->allContentSize = 0;
                                 }
                                 result = LZ4IO_LZ4F_OK;
@@ -1653,7 +2793,7 @@
                     break;
                 }
                 if (totalBlocksSize) {
-                    DISPLAYLEVEL(3, "    %6llu %14s %5s %8s %20llu %20s %9s\n",
+                    if (displayNow) DISPLAYOUT("    %6llu %14s %5s %8s %20llu %20s %9s\n",
                                  cfinfo->frameCount + 1,
                                  LZ4IO_frameTypeNames[frameInfo.frameType],
                                  "-", "-",
@@ -1675,7 +2815,7 @@
                 int const errorNb = fseek_u32(finput, size, SEEK_CUR);
                 if (errorNb != 0)
                     END_PROCESS(43, "Stream error : cannot skip skippable area");
-                DISPLAYLEVEL(3, "    %6llu %14s %5s %8s %20u %20s %9s\n",
+                if (displayNow) DISPLAYOUT("    %6llu %14s %5s %8s %20u %20s %9s\n",
                              cfinfo->frameCount + 1,
                              "SkippableFrame",
                              "-", "-", size + 8, "-", "-");
@@ -1707,7 +2847,7 @@
     int result = 0;
     size_t idx = 0;
     if (g_displayLevel < 3) {
-        DISPLAYOUT("%10s %14s %5s %11s %13s %9s   %s\n",
+        DISPLAYOUT("%10s %14s %5s %11s %13s %8s   %s\n",
                 "Frames", "Type", "Block", "Compressed", "Uncompressed", "Ratio", "Filename");
     }
     for (; idx < ifnIdx; idx++) {
@@ -1718,34 +2858,39 @@
             DISPLAYLEVEL(1, "lz4: %s is not a regular file \n", inFileNames[idx]);
             return 1;
         }
-        DISPLAYLEVEL(3, "%s(%llu/%llu)\n", cfinfo.fileName, (unsigned long long)idx + 1, (unsigned  long long)ifnIdx);
-        DISPLAYLEVEL(3, "    %6s %14s %5s %8s %20s %20s %9s\n",
-                     "Frame", "Type", "Block", "Checksum", "Compressed", "Uncompressed", "Ratio")
-        {   LZ4IO_infoResult const op_result = LZ4IO_getCompressedFileInfo(&cfinfo, inFileNames[idx]);
+        if (g_displayLevel >= 3) {
+            /* verbose mode */
+            DISPLAYOUT("%s(%llu/%llu)\n", cfinfo.fileName, (unsigned long long)idx + 1, (unsigned  long long)ifnIdx);
+            DISPLAYOUT("    %6s %14s %5s %8s %20s %20s %9s\n",
+                        "Frame", "Type", "Block", "Checksum", "Compressed", "Uncompressed", "Ratio");
+        }
+        {   LZ4IO_infoResult const op_result = LZ4IO_getCompressedFileInfo(&cfinfo, inFileNames[idx], g_displayLevel >= 3);
             if (op_result != LZ4IO_LZ4F_OK) {
                 assert(op_result == LZ4IO_format_not_known);
                 DISPLAYLEVEL(1, "lz4: %s: File format not recognized \n", inFileNames[idx]);
                 return 1;
         }   }
-        DISPLAYLEVEL(3, "\n");
+        if (g_displayLevel >= 3) {
+            DISPLAYOUT("\n");
+        }
         if (g_displayLevel < 3) {
-            /* Display Summary */
-            {   char buffers[3][10];
-                DISPLAYOUT("%10llu %14s %5s %11s %13s ",
-                        cfinfo.frameCount,
-                        cfinfo.eqFrameTypes ? LZ4IO_frameTypeNames[cfinfo.frameSummary.frameType] : "-" ,
-                        cfinfo.eqBlockTypes ? LZ4IO_blockTypeID(cfinfo.frameSummary.lz4FrameInfo.blockSizeID,
-                                                                cfinfo.frameSummary.lz4FrameInfo.blockMode, buffers[0]) : "-",
-                        LZ4IO_toHuman((long double)cfinfo.fileSize, buffers[1]),
-                        cfinfo.allContentSize ? LZ4IO_toHuman((long double)cfinfo.frameSummary.lz4FrameInfo.contentSize, buffers[2]) : "-");
-                if (cfinfo.allContentSize) {
-                    double const ratio = (double)cfinfo.fileSize / cfinfo.frameSummary.lz4FrameInfo.contentSize * 100;
-                    DISPLAYOUT("%9.2f%%  %s \n", ratio, cfinfo.fileName);
-                } else {
-                    DISPLAYOUT("%9s   %s\n",
-                            "-",
-                            cfinfo.fileName);
-        }   }   }  /* if (g_displayLevel < 3) */
+            /* Display summary */
+            char buffers[3][10];
+            DISPLAYOUT("%10llu %14s %5s %11s %13s ",
+                    cfinfo.frameCount,
+                    cfinfo.eqFrameTypes ? LZ4IO_frameTypeNames[cfinfo.frameSummary.frameType] : "-" ,
+                    cfinfo.eqBlockTypes ? LZ4IO_blockTypeID(cfinfo.frameSummary.lz4FrameInfo.blockSizeID,
+                                                            cfinfo.frameSummary.lz4FrameInfo.blockMode, buffers[0]) : "-",
+                    LZ4IO_toHuman((long double)cfinfo.fileSize, buffers[1]),
+                    cfinfo.allContentSize ? LZ4IO_toHuman((long double)cfinfo.frameSummary.lz4FrameInfo.contentSize, buffers[2]) : "-");
+            if (cfinfo.allContentSize) {
+                double const ratio = (double)cfinfo.fileSize / (double)cfinfo.frameSummary.lz4FrameInfo.contentSize * 100;
+                DISPLAYOUT("%8.2f%%  %s \n", ratio, cfinfo.fileName);
+            } else {
+                DISPLAYOUT("%8s   %s\n",
+                        "-",
+                        cfinfo.fileName);
+        }   }  /* if (g_displayLevel < 3) */
     }  /* for (; idx < ifnIdx; idx++) */
 
     return result;
diff --git a/programs/lz4io.h b/programs/lz4io.h
index 0cfb1d2..e987d0b 100644
--- a/programs/lz4io.h
+++ b/programs/lz4io.h
@@ -1,6 +1,6 @@
 /*
   LZ4io.h - LZ4 File/Stream Interface
-  Copyright (C) Yann Collet 2011-2020
+  Copyright (C) Yann Collet 2011-2023
   GPL v2 License
 
   This program is free software; you can redistribute it and/or modify
@@ -58,9 +58,9 @@
 void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs);
 
 
-/* ************************************************** */
-/* ****************** Functions ********************* */
-/* ************************************************** */
+/* *************************************************** */
+/* ****************** Processing ********************* */
+/* *************************************************** */
 
 /* if output_filename == stdoutmark, writes to stdout */
 int LZ4IO_compressFilename(const char* input_filename, const char* output_filename, int compressionlevel, const LZ4IO_prefs_t* prefs);
@@ -75,6 +75,9 @@
 /* ****************** Parameters ******************** */
 /* ************************************************** */
 
+int LZ4IO_setNbWorkers(LZ4IO_prefs_t* const prefs, int nbWorkers);
+int LZ4IO_defaultNbWorkers(void);
+
 int LZ4IO_setDictionaryFilename(LZ4IO_prefs_t* const prefs, const char* dictionaryFilename);
 
 /* Default setting : passThrough = 0;
diff --git a/programs/platform.h b/programs/platform.h
index 43a171b..eece7e3 100644
--- a/programs/platform.h
+++ b/programs/platform.h
@@ -48,7 +48,9 @@
   || defined __x86_64__s || defined _M_X64                                                                          /* x86 64-bit */    \
   || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__                                           /* ARM 64-bit */    \
   || (defined __mips  && (__mips == 64 || __mips == 4 || __mips == 3))                                              /* MIPS 64-bit */   \
-  || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */               \
+  || defined __loongarch64                                                                                          /* LoongArch 64-bit */  \
+  || (defined __riscv && defined __riscv_xlen && (__riscv_xlen == 64))                                              /* Riscv 64-bit */  \
+  || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64      /* Cray */               \
   || (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */
 #  if !defined(__64BIT__)
 #    define __64BIT__  1
diff --git a/programs/threadpool.c b/programs/threadpool.c
new file mode 100644
index 0000000..c58f169
--- /dev/null
+++ b/programs/threadpool.c
@@ -0,0 +1,430 @@
+/*
+  threadpool.h - part of lz4 project
+  Copyright (C) Yann Collet 2023
+  GPL v2 License
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License along
+  with this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  You can contact the author at :
+  - LZ4 source repository : https://github.com/lz4/lz4
+  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+
+/* ======   Dependencies   ======= */
+#include <assert.h>
+#include "lz4conf.h"  /* LZ4IO_MULTITHREAD */
+#include "threadpool.h"
+
+
+/* ======   Compiler specifics   ====== */
+#if defined(_MSC_VER)
+#  pragma warning(disable : 4204)        /* disable: C4204: non-constant aggregate initializer */
+#endif
+
+#if !LZ4IO_MULTITHREAD
+
+/* ===================================================== */
+/* Backup implementation with no multi-threading support */
+/* ===================================================== */
+
+/* Non-zero size, to ensure g_poolCtx != NULL */
+struct TPool_s {
+    int dummy;
+};
+static TPool g_poolCtx;
+
+TPool* TPool_create(int numThreads, int queueSize) {
+    (void)numThreads;
+    (void)queueSize;
+    return &g_poolCtx;
+}
+
+void TPool_free(TPool* ctx) {
+    assert(!ctx || ctx == &g_poolCtx);
+    (void)ctx;
+}
+
+void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg) {
+    (void)ctx;
+    job_function(arg);
+}
+
+void TPool_jobsCompleted(TPool* ctx) {
+    assert(!ctx || ctx == &g_poolCtx);
+    (void)ctx;
+}
+
+
+#elif defined(_WIN32)
+
+/* Window TPool implementation using Completion Ports */
+#include <windows.h>
+
+typedef struct TPool_s {
+    HANDLE completionPort;
+    HANDLE* workerThreads;
+    int nbWorkers;
+    int queueSize;
+    LONG nbPendingJobs;
+    HANDLE jobSlotAvail;  /* For queue size control */
+    HANDLE allJobsCompleted; /* Event */
+} TPool;
+
+void TPool_free(TPool* pool)
+{
+    if (!pool) return;
+
+    /* Signal workers to exit by posting NULL completions */
+    {   int i;
+        for (i = 0; i < pool->nbWorkers; i++) {
+            PostQueuedCompletionStatus(pool->completionPort, 0, 0, NULL);
+        }
+    }
+
+    /* Wait for worker threads to finish */
+    WaitForMultipleObjects(pool->nbWorkers, pool->workerThreads, TRUE, INFINITE);
+
+    /* Close thread handles and completion port */
+    {   int i;
+        for (i = 0; i < pool->nbWorkers; i++) {
+            CloseHandle(pool->workerThreads[i]);
+        }
+    }
+    free(pool->workerThreads);
+    CloseHandle(pool->completionPort);
+
+    /* Clean up synchronization objects */
+    CloseHandle(pool->jobSlotAvail);
+    CloseHandle(pool->allJobsCompleted);
+
+    free(pool);
+}
+
+static DWORD WINAPI WorkerThread(LPVOID lpParameter)
+{
+    TPool* const pool = (TPool*)lpParameter;
+    DWORD bytesTransferred;
+    ULONG_PTR completionKey;
+    LPOVERLAPPED overlapped;
+
+    while (GetQueuedCompletionStatus(pool->completionPort,
+                                    &bytesTransferred, &completionKey,
+                                    &overlapped, INFINITE)) {
+
+        /* End signal */
+        if (overlapped == NULL) { break; }
+
+        /* Execute job */
+        ((void (*)(void*))completionKey)(overlapped);
+
+        /* Signal job completion */
+        if (InterlockedDecrement(&pool->nbPendingJobs) == 0) {
+            SetEvent(pool->allJobsCompleted);
+        }
+        ReleaseSemaphore(pool->jobSlotAvail, 1, NULL);
+    }
+
+    return 0;
+}
+
+TPool* TPool_create(int nbWorkers, int queueSize)
+{
+    TPool* pool;
+
+    /* parameters sanitization */
+    if (nbWorkers <= 0 || queueSize <= 0) return NULL;
+    if (nbWorkers>LZ4_NBWORKERS_MAX) nbWorkers=LZ4_NBWORKERS_MAX;
+
+    pool = calloc(1, sizeof(TPool));
+    if (!pool) return NULL;
+
+    /* Create completion port */
+    pool->completionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, nbWorkers);
+    if (!pool->completionPort) { goto _cleanup; }
+
+    /* Create worker threads */
+    pool->nbWorkers = nbWorkers;
+    pool->workerThreads = (HANDLE*)malloc(sizeof(HANDLE) * nbWorkers);
+    if (pool->workerThreads == NULL) { goto _cleanup; }
+
+    {   int i;
+        for (i = 0; i < nbWorkers; i++) {
+            pool->workerThreads[i] = CreateThread(NULL, 0, WorkerThread, pool, 0, NULL);
+            if (!pool->workerThreads[i]) { goto _cleanup; }
+        }
+    }
+
+    /* Initialize sync objects members */
+    pool->queueSize = queueSize;
+    pool->nbPendingJobs = 0;
+
+    pool->jobSlotAvail = CreateSemaphore(NULL, queueSize+nbWorkers, queueSize+nbWorkers, NULL);
+    if (!pool->jobSlotAvail) { goto _cleanup; }
+
+    pool->allJobsCompleted = CreateEvent(NULL, FALSE, FALSE, NULL);
+    if (!pool->allJobsCompleted) { goto _cleanup; }
+
+    return pool;
+
+_cleanup:
+    TPool_free(pool);
+    return NULL;
+}
+
+
+void TPool_submitJob(TPool* pool, void (*job_function)(void*), void* arg)
+{
+    assert(pool);
+
+    /* Atomically increment pending jobs and check for overflow */
+    WaitForSingleObject(pool->jobSlotAvail, INFINITE);
+    ResetEvent(pool->allJobsCompleted);
+    InterlockedIncrement(&pool->nbPendingJobs);
+
+    /* Post the job directly to the completion port */
+    PostQueuedCompletionStatus(pool->completionPort,
+                               0, /* Bytes transferred not used */
+                               (ULONG_PTR)job_function, /* Store function pointer in completionKey */
+                               (LPOVERLAPPED)arg);      /* Store argument in overlapped */
+}
+
+void TPool_jobsCompleted(TPool* pool)
+{
+    assert(pool);
+    WaitForSingleObject(pool->allJobsCompleted, INFINITE);
+}
+
+#else
+
+/* pthread availability assumed */
+#include <stdlib.h>  /* malloc, free */
+#include <pthread.h> /* pthread_* */
+
+/* A job is just a function with an opaque argument */
+typedef struct TPool_job_s {
+    void (*job_function)(void*);
+    void *arg;
+} TPool_job;
+
+struct TPool_s {
+    pthread_t* threads;
+    size_t threadCapacity;
+    size_t threadLimit;
+
+    /* The queue is a circular buffer */
+    TPool_job* queue;
+    size_t queueHead;
+    size_t queueTail;
+    size_t queueSize;
+
+    /* The number of threads working on jobs */
+    size_t numThreadsBusy;
+    /* Indicates if the queue is empty */
+    int queueEmpty;
+
+    /* The mutex protects the queue */
+    pthread_mutex_t queueMutex;
+    /* Condition variable for pushers to wait on when the queue is full */
+    pthread_cond_t queuePushCond;
+    /* Condition variables for poppers to wait on when the queue is empty */
+    pthread_cond_t queuePopCond;
+    /* Indicates if the queue is shutting down */
+    int shutdown;
+};
+
+static void TPool_shutdown(TPool* ctx);
+
+void TPool_free(TPool* ctx) {
+    if (!ctx) { return; }
+    TPool_shutdown(ctx);
+    pthread_mutex_destroy(&ctx->queueMutex);
+    pthread_cond_destroy(&ctx->queuePushCond);
+    pthread_cond_destroy(&ctx->queuePopCond);
+    free(ctx->queue);
+    free(ctx->threads);
+    free(ctx);
+}
+
+static void* TPool_thread(void* opaque);
+
+TPool* TPool_create(int nbThreads, int queueSize)
+{
+    TPool* ctx;
+    /* Check parameters */
+    if (nbThreads<1 || queueSize<1) { return NULL; }
+    /* Allocate the context and zero initialize */
+    ctx = (TPool*)calloc(1, sizeof(TPool));
+    if (!ctx) { return NULL; }
+    /* init pthread variables */
+    {   int error = 0;
+        error |= pthread_mutex_init(&ctx->queueMutex, NULL);
+        error |= pthread_cond_init(&ctx->queuePushCond, NULL);
+        error |= pthread_cond_init(&ctx->queuePopCond, NULL);
+        if (error) { TPool_free(ctx); return NULL; }
+    }
+    /* Initialize the job queue.
+     * It needs one extra space since one space is wasted to differentiate
+     * empty and full queues.
+     */
+    ctx->queueSize = (size_t)queueSize + 1;
+    ctx->queue = (TPool_job*)calloc(1, ctx->queueSize * sizeof(TPool_job));
+    if (ctx->queue == NULL) {
+        TPool_free(ctx);
+        return NULL;
+    }
+    ctx->queueHead = 0;
+    ctx->queueTail = 0;
+    ctx->numThreadsBusy = 0;
+    ctx->queueEmpty = 1;
+    ctx->shutdown = 0;
+    /* Allocate space for the thread handles */
+    ctx->threads = (pthread_t*)calloc(1, (size_t)nbThreads * sizeof(pthread_t));
+    if (ctx->threads == NULL) {
+        TPool_free(ctx);
+        return NULL;
+    }
+    ctx->threadCapacity = 0;
+    /* Initialize the threads */
+    {   int i;
+        for (i = 0; i < nbThreads; ++i) {
+            if (pthread_create(&ctx->threads[i], NULL, &TPool_thread, ctx)) {
+                ctx->threadCapacity = (size_t)i;
+                TPool_free(ctx);
+                return NULL;
+        }   }
+        ctx->threadCapacity = (size_t)nbThreads;
+        ctx->threadLimit = (size_t)nbThreads;
+    }
+    return ctx;
+}
+
+/* TPool_thread() :
+ * Work thread for the thread pool.
+ * Waits for jobs and executes them.
+ * @returns : NULL on failure else non-null.
+ */
+static void* TPool_thread(void* opaque) {
+    TPool* const ctx = (TPool*)opaque;
+    if (!ctx) { return NULL; }
+    for (;;) {
+        /* Lock the mutex and wait for a non-empty queue or until shutdown */
+        pthread_mutex_lock(&ctx->queueMutex);
+
+        while ( ctx->queueEmpty
+            || (ctx->numThreadsBusy >= ctx->threadLimit) ) {
+            if (ctx->shutdown) {
+                /* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
+                 * a few threads will be shutdown while !queueEmpty,
+                 * but enough threads will remain active to finish the queue */
+                pthread_mutex_unlock(&ctx->queueMutex);
+                return opaque;
+            }
+            pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
+        }
+        /* Pop a job off the queue */
+        {   TPool_job const job = ctx->queue[ctx->queueHead];
+            ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
+            ctx->numThreadsBusy++;
+            ctx->queueEmpty = (ctx->queueHead == ctx->queueTail);
+            /* Unlock the mutex, signal a pusher, and run the job */
+            pthread_cond_signal(&ctx->queuePushCond);
+            pthread_mutex_unlock(&ctx->queueMutex);
+
+            job.job_function(job.arg);
+
+            /* If the intended queue size was 0, signal after finishing job */
+            pthread_mutex_lock(&ctx->queueMutex);
+            ctx->numThreadsBusy--;
+            pthread_cond_signal(&ctx->queuePushCond);
+            pthread_mutex_unlock(&ctx->queueMutex);
+        }
+    }  /* for (;;) */
+    assert(0);  /* Unreachable */
+}
+
+/*! TPool_shutdown() :
+    Shutdown the queue, wake any sleeping threads, and join all of the threads.
+*/
+static void TPool_shutdown(TPool* ctx) {
+    /* Shut down the queue */
+    pthread_mutex_lock(&ctx->queueMutex);
+    ctx->shutdown = 1;
+    pthread_mutex_unlock(&ctx->queueMutex);
+    /* Wake up sleeping threads */
+    pthread_cond_broadcast(&ctx->queuePushCond);
+    pthread_cond_broadcast(&ctx->queuePopCond);
+    /* Join all of the threads */
+    {   size_t i;
+        for (i = 0; i < ctx->threadCapacity; ++i) {
+            pthread_join(ctx->threads[i], NULL);  /* note : could fail */
+    }   }
+}
+
+
+/*! TPool_jobsCompleted() :
+ *  Waits for all queued jobs to finish executing.
+ */
+void TPool_jobsCompleted(TPool* ctx){
+    pthread_mutex_lock(&ctx->queueMutex);
+    while(!ctx->queueEmpty || ctx->numThreadsBusy > 0) {
+        pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
+    }
+    pthread_mutex_unlock(&ctx->queueMutex);
+}
+
+/**
+ * Returns 1 if the queue is full and 0 otherwise.
+ *
+ * When queueSize is 1 (pool was created with an intended queueSize of 0),
+ * then a queue is empty if there is a thread free _and_ no job is waiting.
+ */
+static int isQueueFull(TPool const* ctx) {
+    if (ctx->queueSize > 1) {
+        return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
+    } else {
+        return (ctx->numThreadsBusy == ctx->threadLimit) ||
+               !ctx->queueEmpty;
+    }
+}
+
+static void
+TPool_submitJob_internal(TPool* ctx, void (*job_function)(void*), void *arg)
+{
+    TPool_job job;
+    job.job_function = job_function;
+    job.arg = arg;
+    assert(ctx != NULL);
+    if (ctx->shutdown) return;
+
+    ctx->queueEmpty = 0;
+    ctx->queue[ctx->queueTail] = job;
+    ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
+    pthread_cond_signal(&ctx->queuePopCond);
+}
+
+void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg)
+{
+    assert(ctx != NULL);
+    pthread_mutex_lock(&ctx->queueMutex);
+    /* Wait until there is space in the queue for the new job */
+    while (isQueueFull(ctx) && (!ctx->shutdown)) {
+        pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
+    }
+    TPool_submitJob_internal(ctx, job_function, arg);
+    pthread_mutex_unlock(&ctx->queueMutex);
+}
+
+#endif  /* LZ4IO_NO_MT */
diff --git a/programs/threadpool.h b/programs/threadpool.h
new file mode 100644
index 0000000..5ea121d
--- /dev/null
+++ b/programs/threadpool.h
@@ -0,0 +1,68 @@
+/*
+  threadpool.h - part of lz4 project
+  Copyright (C) Yann Collet 2023
+  GPL v2 License
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License along
+  with this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  You can contact the author at :
+  - LZ4 source repository : https://github.com/lz4/lz4
+  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+#ifndef THREADPOOL_H
+#define THREADPOOL_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+typedef struct TPool_s TPool;
+
+/*! TPool_create() :
+ *  Create a thread pool with at most @nbThreads.
+ * @nbThreads must be at least 1.
+ * @queueSize is the maximum number of pending jobs before blocking.
+ * @return : TPool* pointer on success, else NULL.
+*/
+TPool* TPool_create(int nbThreads, int queueSize);
+
+/*! TPool_free() :
+ *  Free a thread pool returned by TPool_create().
+ *  Waits for the completion of running jobs before freeing resources.
+ */
+void TPool_free(TPool* ctx);
+
+/*! TPool_submitJob() :
+ *  Add @job_function(arg) to the thread pool.
+ * @ctx must be valid.
+ *  Invocation can block if queue is full.
+ *  Note: Ensure @arg's lifetime extends until @job_function completes.
+ *  Alternatively, @arg's lifetime must be managed by @job_function.
+ */
+void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg);
+
+/*! TPool_jobsCompleted() :
+ *  Blocks until all queued jobs are completed.
+ */
+void TPool_jobsCompleted(TPool* ctx);
+
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* THREADPOOL_H */
diff --git a/programs/timefn.c b/programs/timefn.c
new file mode 100644
index 0000000..ef2e238
--- /dev/null
+++ b/programs/timefn.c
@@ -0,0 +1,175 @@
+/*
+  timefn.c - portable time measurement functions
+  Copyright (C) Yann Collet 2023
+
+  GPL v2 License
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License along
+  with this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  You can contact the author at :
+  - LZ4 source repository : https://github.com/lz4/lz4
+  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/* ===  Dependencies  === */
+
+#include "timefn.h"
+#include <time.h> /* CLOCK_MONOTONIC, TIME_UTC */
+
+/*-****************************************
+ *  Time functions
+ ******************************************/
+
+#if defined(_WIN32) /* Windows */
+
+#    include <stdio.h>   /* perror */
+#    include <stdlib.h>  /* abort */
+#    include <windows.h> /* LARGE_INTEGER */
+
+TIME_t TIME_getTime(void)
+{
+    static LARGE_INTEGER ticksPerSecond;
+    static int init = 0;
+    if (!init) {
+        if (!QueryPerformanceFrequency(&ticksPerSecond)) {
+            perror("timefn::QueryPerformanceFrequency");
+            abort();
+        }
+        init = 1;
+    }
+    {
+        TIME_t r;
+        LARGE_INTEGER x;
+        QueryPerformanceCounter(&x);
+        r.t = (Duration_ns)(x.QuadPart * 1000000000ULL / ticksPerSecond.QuadPart);
+        return r;
+    }
+}
+
+#elif defined(__APPLE__) && defined(__MACH__)
+
+#    include <mach/mach_time.h> /* mach_timebase_info_data_t, mach_timebase_info, mach_absolute_time */
+
+TIME_t TIME_getTime(void)
+{
+    static mach_timebase_info_data_t rate;
+    static int init = 0;
+    if (!init) {
+        mach_timebase_info(&rate);
+        init = 1;
+    }
+    {
+        TIME_t r;
+        r.t = mach_absolute_time() * (Duration_ns)rate.numer
+                / (Duration_ns)rate.denom;
+        return r;
+    }
+}
+
+
+/* POSIX.1-2001 (optional) */
+#elif defined(CLOCK_MONOTONIC)
+
+#include <stdlib.h>   /* abort */
+#include <stdio.h>    /* perror */
+
+TIME_t TIME_getTime(void)
+{
+    /* time must be initialized, othersize it may fail msan test.
+     * No good reason, likely a limitation of timespec_get() for some target */
+    struct timespec time = { 0, 0 };
+    if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) {
+        perror("timefn::clock_gettime(CLOCK_MONOTONIC)");
+        abort();
+    }
+    {   TIME_t r;
+        r.t = (Duration_ns)time.tv_sec * 1000000000ULL
+                + (Duration_ns)time.tv_nsec;
+        return r;
+    }
+}
+
+
+/* C11 requires support of timespec_get().
+ * However, FreeBSD 11 claims C11 compliance while lacking timespec_get().
+ * Double confirm timespec_get() support by checking the definition of TIME_UTC.
+ * However, some versions of Android manage to simultaneously define TIME_UTC
+ * and lack timespec_get() support... */
+#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */) \
+        && defined(TIME_UTC) && !defined(__ANDROID__)
+
+#    include <stdio.h>  /* perror */
+#    include <stdlib.h> /* abort */
+
+TIME_t TIME_getTime(void)
+{
+    /* time must be initialized, othersize it may fail msan test */
+    struct timespec time = { 0, 0 };
+    if (timespec_get(&time, TIME_UTC) != TIME_UTC) {
+        perror("timefn::timespec_get(TIME_UTC)");
+        abort();
+    }
+    {
+        TIME_t r;
+        r.t = (Duration_ns)time.tv_sec * 1000000000ULL
+                + (Duration_ns)time.tv_nsec;
+        return r;
+    }
+}
+
+#else /* relies on standard C90 (note : clock_t produces wrong measurements \
+         for multi-threaded workloads) */
+
+TIME_t TIME_getTime(void)
+{
+    TIME_t r;
+    r.t = (Duration_ns)clock() * 1000000000ULL / CLOCKS_PER_SEC;
+    return r;
+}
+
+#    define TIME_MT_MEASUREMENTS_NOT_SUPPORTED
+
+#endif
+
+/* ==== Common functions, valid for all time API ==== */
+
+Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd)
+{
+    return clockEnd.t - clockStart.t;
+}
+
+Duration_ns TIME_clockSpan_ns(TIME_t clockStart)
+{
+    TIME_t const clockEnd = TIME_getTime();
+    return TIME_span_ns(clockStart, clockEnd);
+}
+
+void TIME_waitForNextTick(void)
+{
+    TIME_t const clockStart = TIME_getTime();
+    TIME_t clockEnd;
+    do {
+        clockEnd = TIME_getTime();
+    } while (TIME_span_ns(clockStart, clockEnd) == 0);
+}
+
+int TIME_support_MT_measurements(void)
+{
+#if defined(TIME_MT_MEASUREMENTS_NOT_SUPPORTED)
+    return 0;
+#else
+    return 1;
+#endif
+}
diff --git a/programs/timefn.h b/programs/timefn.h
new file mode 100644
index 0000000..e675a02
--- /dev/null
+++ b/programs/timefn.h
@@ -0,0 +1,72 @@
+/*
+  timefn.h - portable time measurement functions
+  Copyright (C) Yann Collet 2023
+
+  GPL v2 License
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License along
+  with this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  You can contact the author at :
+  - LZ4 source repository : https://github.com/lz4/lz4
+  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+#ifndef TIMEFN
+#define TIMEFN
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/*-****************************************
+ *  Types
+ ******************************************/
+
+typedef unsigned long long Duration_ns;
+
+/* TIME_t contains a nanosecond time counter.
+ * The absolute value is not meaningful.
+ * It's only valid to compute Duration_ns between 2 measurements. */
+typedef struct {
+    Duration_ns t;
+} TIME_t;
+#define TIME_INITIALIZER { 0 }
+
+/*-****************************************
+ *  Time functions
+ ******************************************/
+
+/* @return a TIME_t value to be compared to another one in order to compute a duration.
+ * The absolute value returned is meaningless */
+TIME_t TIME_getTime(void);
+
+/* Timer resolution can be low on some platforms.
+ * To improve accuracy, it's recommended to wait for a new tick
+ * before starting benchmark measurements */
+void TIME_waitForNextTick(void);
+
+/* tells if TIME_getTime() returns correct time measurements
+ * in scenarios involving multi-threaded workload.
+ * note : this is not the case if only C90 clock_t measurements are available */
+int TIME_support_MT_measurements(void);
+
+Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd);
+Duration_ns TIME_clockSpan_ns(TIME_t clockStart);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* TIMEFN */
diff --git a/programs/util.c b/programs/util.c
new file mode 100644
index 0000000..170b5a7
--- /dev/null
+++ b/programs/util.c
@@ -0,0 +1,165 @@
+/*
+    util.h - utility functions
+    Copyright (C) 2023, Yann Collet
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/*-****************************************
+*  Dependencies
+******************************************/
+#include "util.h"   /* note : ensure that platform.h is included first ! */
+
+/*-****************************************
+*  count the number of cores
+******************************************/
+
+#if defined(_WIN32)
+
+#include <windows.h>
+
+int UTIL_countCores(void)
+{
+    static int numCores = 0;
+    if (numCores != 0) return numCores;
+
+    {   SYSTEM_INFO sysinfo;
+        GetSystemInfo(&sysinfo);
+        numCores = sysinfo.dwNumberOfProcessors;
+    }
+
+    if (numCores == 0) {
+        /* Unexpected result, fall back on 1 */
+        return numCores = 1;
+    }
+
+    return numCores;
+}
+
+#elif defined(__APPLE__)
+
+#include <sys/sysctl.h>
+
+/* Use apple-provided syscall
+ * see: man 3 sysctl */
+int UTIL_countCores(void)
+{
+    static S32 numCores = 0; /* apple specifies int32_t */
+    if (numCores != 0) return (int)numCores;
+
+    {   size_t size = sizeof(S32);
+        int const ret = sysctlbyname("hw.logicalcpu", &numCores, &size, NULL, 0);
+        if (ret != 0) {
+            /* error: fall back on 1 */
+            numCores = 1;
+        }
+    }
+    return (int)numCores;
+}
+
+#elif defined(__linux__)
+
+int UTIL_countCores(void)
+{
+    static int numCores = 0;
+
+    if (numCores != 0) return numCores;
+
+    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
+    if (numCores == -1) {
+        /* value not queryable, fall back on 1 */
+        return numCores = 1;
+    }
+
+    return numCores;
+}
+
+#elif defined(__FreeBSD__)
+
+#include <stdio.h>  /* perror */
+#include <errno.h>
+#include <sys/param.h>
+#include <sys/sysctl.h>
+
+/* Use physical core sysctl when available
+ * see: man 4 smp, man 3 sysctl */
+int UTIL_countCores(void)
+{
+    static int numCores = 0; /* freebsd sysctl is native int sized */
+    if (numCores != 0) return numCores;
+
+#if __FreeBSD_version >= 1300008
+    {   size_t size = sizeof(numCores);
+        int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0);
+        if (ret == 0) {
+            int perCore = 1;
+            ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0);
+            /* default to physical cores if logical cannot be read */
+            if (ret != 0) /* error */
+                return numCores;
+            numCores *= perCore;
+            return numCores;
+        }
+        if (errno != ENOENT) {
+            perror("lz4: can't get number of cpus");
+            exit(1);
+        }
+        /* sysctl not present, fall through to older sysconf method */
+    }
+#endif
+
+    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
+    if (numCores == -1) {
+        /* value not queryable, fall back on 1 */
+        numCores = 1;
+    }
+    return numCores;
+}
+
+#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
+
+/* Use POSIX sysconf
+ * see: man 3 sysconf */
+int UTIL_countCores(void)
+{
+    static int numCores = 0;
+    if (numCores != 0) return numCores;
+
+    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
+    if (numCores == -1) {
+        /* value not queryable, fall back on 1 */
+        numCores = 1;
+    }
+    return numCores;
+}
+
+#else
+
+int UTIL_countCores(void)
+{
+    /* no clue */
+    return 1;
+}
+
+#endif
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/programs/util.h b/programs/util.h
index 3192ddc..88efe05 100644
--- a/programs/util.h
+++ b/programs/util.h
@@ -1,6 +1,6 @@
 /*
     util.h - utility functions
-    Copyright (C) 2016-2020, Przemyslaw Skibinski, Yann Collet
+    Copyright (C) 2016-2023, Przemyslaw Skibinski, Yann Collet
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -91,6 +91,10 @@
 #   define UTIL_fseek fseek
 #endif
 
+/*-****************************************
+*  Local host Core counting
+******************************************/
+int UTIL_countCores(void);
 
 /*-****************************************
 *  Sleep functions: Windows - Posix - others
@@ -195,148 +199,16 @@
 /*-****************************************
 *  String functions
 ******************************************/
-/*
- * A modified version of realloc().
- * If UTIL_realloc() fails the original block is freed.
-*/
+/* supports a==NULL or b==NULL */
 UTIL_STATIC int UTIL_sameString(const char* a, const char* b)
 {
-    assert(a!=NULL && b!=NULL);  /* unsupported scenario */
+    assert(a != NULL || b != NULL);  /* unsupported scenario */
     if (a==NULL) return 0;
     if (b==NULL) return 0;
     return !strcmp(a,b);
 }
 
 
-/*-****************************************
-*  Time functions
-******************************************/
-#if defined(_WIN32)   /* Windows */
-
-    typedef LARGE_INTEGER UTIL_time_t;
-    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
-    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
-    {
-        static LARGE_INTEGER ticksPerSecond;
-        static int init = 0;
-        if (!init) {
-            if (!QueryPerformanceFrequency(&ticksPerSecond))
-                fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
-            init = 1;
-        }
-        return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
-    }
-    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
-    {
-        static LARGE_INTEGER ticksPerSecond;
-        static int init = 0;
-        if (!init) {
-            if (!QueryPerformanceFrequency(&ticksPerSecond))
-                fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
-            init = 1;
-        }
-        return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
-    }
-
-#elif defined(__APPLE__) && defined(__MACH__)
-
-    #include <mach/mach_time.h>
-    typedef U64 UTIL_time_t;
-    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
-    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
-    {
-        static mach_timebase_info_data_t rate;
-        static int init = 0;
-        if (!init) {
-            mach_timebase_info(&rate);
-            init = 1;
-        }
-        return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom)) / 1000ULL;
-    }
-    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
-    {
-        static mach_timebase_info_data_t rate;
-        static int init = 0;
-        if (!init) {
-            mach_timebase_info(&rate);
-            init = 1;
-        }
-        return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
-    }
-
-#elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || (defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2) ) )
-
-    #include <time.h>
-    typedef struct timespec UTIL_time_t;
-    UTIL_STATIC UTIL_time_t UTIL_getTime(void)
-    {
-        UTIL_time_t now;
-        if (clock_gettime(CLOCK_MONOTONIC, &now))
-            fprintf(stderr, "ERROR: Failed to get time\n");   /* we could also exit() */
-        return now;
-    }
-    UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
-    {
-        UTIL_time_t diff;
-        if (end.tv_nsec < begin.tv_nsec) {
-            diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
-            diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
-        } else {
-            diff.tv_sec = end.tv_sec - begin.tv_sec;
-            diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
-        }
-        return diff;
-    }
-    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
-    {
-        UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
-        U64 micro = 0;
-        micro += 1000000ULL * diff.tv_sec;
-        micro += diff.tv_nsec / 1000ULL;
-        return micro;
-    }
-    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
-    {
-        UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
-        U64 nano = 0;
-        nano += 1000000000ULL * diff.tv_sec;
-        nano += diff.tv_nsec;
-        return nano;
-    }
-
-#else   /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
-
-    typedef clock_t UTIL_time_t;
-    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
-    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
-    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
-#endif
-
-
-/* returns time span in microseconds */
-UTIL_STATIC U64 UTIL_clockSpanMicro(UTIL_time_t clockStart)
-{
-    UTIL_time_t const clockEnd = UTIL_getTime();
-    return UTIL_getSpanTimeMicro(clockStart, clockEnd);
-}
-
-/* returns time span in nanoseconds */
-UTIL_STATIC U64 UTIL_clockSpanNano(UTIL_time_t clockStart)
-{
-    UTIL_time_t const clockEnd = UTIL_getTime();
-    return UTIL_getSpanTimeNano(clockStart, clockEnd);
-}
-
-UTIL_STATIC void UTIL_waitForNextTick(void)
-{
-    UTIL_time_t const clockStart = UTIL_getTime();
-    UTIL_time_t clockEnd;
-    do {
-        clockEnd = UTIL_getTime();
-    } while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
-}
-
-
 
 /*-****************************************
 *  File functions
@@ -412,7 +284,6 @@
     return 1;
 }
 
-
 UTIL_STATIC int UTIL_isRegFD(int fd)
 {
     stat_t statbuf;
@@ -423,26 +294,25 @@
     return UTIL_getFDStat(fd, &statbuf); /* Only need to know whether it is a regular file */
 }
 
-
 UTIL_STATIC int UTIL_isRegFile(const char* infilename)
 {
     stat_t statbuf;
     return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
 }
 
-
-UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
+UTIL_STATIC int UTIL_isDirectory(const char* infilename)
 {
-    int r;
     stat_t statbuf;
+    int r;
 #if defined(_MSC_VER)
     r = _stat64(infilename, &statbuf);
-    if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
+    if (r) return 0;
+    return (statbuf.st_mode & S_IFDIR);
 #else
     r = stat(infilename, &statbuf);
-    if (!r && S_ISDIR(statbuf.st_mode)) return 1;
+    if (r) return 0;
+    return (S_ISDIR(statbuf.st_mode));
 #endif
-    return 0;
 }
 
 
diff --git a/tests/.gitignore b/tests/.gitignore
index c7d8f19..48ae042 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -5,6 +5,8 @@
 frametest32
 fullbench
 fullbench32
+fullbench-lib
+fullbench-dll
 fuzzer
 fuzzer32
 fasttest
diff --git a/tests/COPYING b/tests/COPYING
index d159169..c728282 100644
--- a/tests/COPYING
+++ b/tests/COPYING
@@ -1,339 +1,83 @@
-                    GNU GENERAL PUBLIC LICENSE
-                       Version 2, June 1991
+Full name:
+GNU General Public License v2.0 or later
 
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+Short identifier:
+GPL-2.0-or-later
 
-                            Preamble
+Text:
+GNU GENERAL PUBLIC LICENSE
+Version 2, June 1991
 
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.)  You can apply it to
-your programs, too.
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
 
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
+Preamble
 
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
 
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
 
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
+To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
 
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
 
-  The precise terms and conditions for copying, distribution and
-modification follow.
+We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
 
-                    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
 
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
+Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
 
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
+The precise terms and conditions for copying, distribution and modification follow.
 
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
+0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
 
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
+1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
 
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
+2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
+b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
+c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
 
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
 
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
+In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
 
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
+3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
+a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
 
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
+If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
 
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
+4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
 
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
+5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
 
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
+6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
 
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
+7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
 
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
 
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
 
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
+8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
 
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
+9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
 
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
+10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+NO WARRANTY
 
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-                            NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-            How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
-    You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) year name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
diff --git a/tests/Makefile b/tests/Makefile
index 93a5581..47e2774 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -28,20 +28,20 @@
 # datagen : generates synthetic data samples for tests & benchmarks
 # ##########################################################################
 
-LZ4DIR  := ../lib
+LIBDIR  := ../lib
 PRGDIR  := ../programs
 TESTDIR := versionsTest
 PYTHON  ?= python3
 
 DEBUGLEVEL?= 1
 DEBUGFLAGS = -g -DLZ4_DEBUG=$(DEBUGLEVEL)
-CFLAGS  ?= -O3 # can select custom optimization flags. Example : CFLAGS=-O2 make
-CFLAGS  += -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
-           -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
-           -Wpointer-arith -Wstrict-aliasing=1
-CFLAGS  += $(DEBUGFLAGS) $(MOREFLAGS)
-CPPFLAGS+= -I$(LZ4DIR) -I$(PRGDIR) -DXXH_NAMESPACE=LZ4_
-FLAGS    = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
+USERCFLAGS:= -O3 $(CFLAGS) # appended for higher priority
+WFLAGS    = -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
+            -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
+            -Wpointer-arith -Wstrict-aliasing=1
+CFLAGS    = $(WFLAGS) $(DEBUGFLAGS) $(USERCFLAGS)
+CPPFLAGS += -I$(LIBDIR) -I$(PRGDIR) -DXXH_NAMESPACE=LZ4_
+ALLFLAGS  = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
 
 include ../Makefile.inc
 
@@ -56,83 +56,97 @@
 .PHONY: default
 default: all
 
+.PHONY: all
 all: fullbench fuzzer frametest roundTripTest datagen checkFrame decompress-partial
 
+.PHONY: all32
 all32: CFLAGS+=-m32
 all32: all
 
+.PHONY: lz4
 lz4:
 	$(MAKE) -C $(PRGDIR) $@ CFLAGS="$(CFLAGS)"
 
+.PHONY: lib liblz4.pc
 lib liblz4.pc:
-	$(MAKE) -C $(LZ4DIR) $@ CFLAGS="$(CFLAGS)"
+	$(MAKE) -C $(LIBDIR) $@ CFLAGS="$(CFLAGS)"
 
 lz4c unlz4 lz4cat: lz4
 	$(LN_SF) $(LZ4) $(PRGDIR)/$@
 
-lz4c32:   # create a 32-bits version for 32/64 interop tests
+.PHONY: lz4c32
+lz4c32:  # create a 32-bits version for 32/64 interop tests
 	$(MAKE) -C $(PRGDIR) $@ CFLAGS="-m32 $(CFLAGS)"
 
-%.o : $(LZ4DIR)/%.c $(LZ4DIR)/%.h
+# *.o objects are from library
+%.o : $(LIBDIR)/%.c $(LIBDIR)/%.h
 	$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
 
+CLEAN += fullbench
 fullbench : DEBUGLEVEL=0
+fullbench : CPPFLAGS += -DNDEBUG
 fullbench : lz4.o lz4hc.o lz4frame.o xxhash.o fullbench.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
-$(LZ4DIR)/liblz4.a:
-	$(MAKE) -C $(LZ4DIR) liblz4.a
+.PHONY: $(LIBDIR)/liblz4.a
+$(LIBDIR)/liblz4.a:
+	$(MAKE) -C $(LIBDIR) liblz4.a
 
-fullbench-lib: fullbench.c $(LZ4DIR)/liblz4.a
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+CLEAN += fullbench-lib
+fullbench-lib : DEBUGLEVEL=0
+fullbench-lib : CPPFLAGS += -DNDEBUG
+fullbench-lib: fullbench.c $(LIBDIR)/liblz4.a
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
-fullbench-dll: fullbench.c $(LZ4DIR)/xxhash.c
-	$(MAKE) -C $(LZ4DIR) liblz4
-	$(CC) $(FLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(LZ4DIR)/dll/$(LIBLZ4).dll
+# Note: Windows only
+ifeq ($(WINBASED),yes)
+CLEAN += fullbench-dll
+fullbench-dll : DEBUGLEVEL=0
+fullbench-dll : CPPFLAGS += -DNDEBUG
+fullbench-dll: fullbench.c $(LIBDIR)/xxhash.c
+	$(MAKE) -C $(LIBDIR) liblz4
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(LIBDIR)/dll/$(LIBLZ4).dll
+endif
 
 # test LZ4_USER_MEMORY_FUNCTIONS
 fullbench-wmalloc: CPPFLAGS += -DLZ4_USER_MEMORY_FUNCTIONS
 fullbench-wmalloc: fullbench
 
+CLEAN += fuzzer
 fuzzer  : lz4.o lz4hc.o xxhash.o fuzzer.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
+CLEAN += frametest
 frametest: lz4frame.o lz4.o lz4hc.o xxhash.o frametest.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
+CLEAN += roundTripTest
 roundTripTest : lz4.o lz4hc.o xxhash.o roundTripTest.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
-datagen : $(PRGDIR)/datagen.c datagencli.c
-	$(CC) $(FLAGS) -I$(PRGDIR) $^ -o $@$(EXT)
+CLEAN += datagen
+datagen: CPPFLAGS+=-DNDEBUG
+datagen : datagen.c $(PRGDIR)/lorem.c loremOut.c datagencli.c
+	$(CC) $(ALLFLAGS) -I$(PRGDIR) $^ -o $@$(EXT)
 
+CLEAN += checkFrame
 checkFrame : lz4frame.o lz4.o lz4hc.o xxhash.o checkFrame.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
+CLEAN += decompress-partial
 decompress-partial: lz4.o decompress-partial.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
+CLEAN += decompress-partial-usingDict
 decompress-partial-usingDict: lz4.o decompress-partial-usingDict.c
-	$(CC) $(FLAGS) $^ -o $@$(EXT)
-
-freestanding: freestanding.c
-	$(CC) -ffreestanding -nostdlib $^ -o $@$(EXT)
+	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
 
 .PHONY: clean
 clean:
-	@$(MAKE) -C $(LZ4DIR) $@ > $(VOID)
+	@$(MAKE) -C $(LIBDIR) $@ > $(VOID)
 	@$(MAKE) -C $(PRGDIR) $@ > $(VOID)
-	@$(RM) -rf core *.o *.test tmp* \
-        fullbench-dll$(EXT) fullbench-lib$(EXT) \
-        fullbench$(EXT) fullbench32$(EXT) \
-        fuzzer$(EXT) fuzzer32$(EXT) \
-        frametest$(EXT) frametest32$(EXT) \
-        fasttest$(EXT) roundTripTest$(EXT) \
-        datagen$(EXT) checkTag$(EXT) \
-        frameTest$(EXT) decompress-partial$(EXT) \
-        abiTest$(EXT) freestanding$(EXT) \
-        lz4_all.c
-	@$(RM) -rf $(TESTDIR)
+	@$(RM) $(CLEAN) core *.o *.test tmp*
+	@$(RM) -r $(TESTDIR)
 	@echo Cleaning completed
 
 .PHONY: versionsTest
@@ -143,67 +157,63 @@
 listTest: lz4
 	QEMU_SYS=$(QEMU_SYS) $(PYTHON) test-lz4-list.py
 
+# Note: requires liblz4 installed
+CLEAN += abiTest
 abiTest: LDLIBS += -llz4
 
 .PHONY: abiTests
 abiTests:
 	$(PYTHON) test-lz4-abi.py
 
-checkTag: checkTag.c $(LZ4DIR)/lz4.h
-	$(CC) $(FLAGS) $< -o $@$(EXT)
+CLEAN += checkTag
+checkTag: checkTag.c $(LIBDIR)/lz4.h
+	$(CC) $(ALLFLAGS) $< -o $@$(EXT)
 
 #-----------------------------------------------------------------------------
 # validated only for Linux, OSX, BSD, Hurd and Solaris targets
 #-----------------------------------------------------------------------------
 ifeq ($(POSIX_ENV),Yes)
 
-MD5:=md5sum
-ifneq (,$(filter $(shell $(UNAME)), Darwin ))
-MD5:=md5 -r
-endif
-
-# note : we should probably settle on a single compare utility
-CMP:=cmp
-GREP:=grep
-DIFF:=diff
-ifneq (,$(filter $(shell $(UNAME)),SunOS))
-DIFF:=gdiff
-endif
-
-CAT:=cat
-DD:=dd
-DATAGEN:=./datagen
+MD5 ?= $(if $(filter Darwin,$(shell $(UNAME))),md5 -r,md5sum)
+GREP?= grep
+CAT ?= cat
+DATAGEN?=./datagen
+PATH:=../programs:$(shell pwd):$(PATH)
 
 .PHONY: list
 list:
-	@$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs
+	$(GREP) '^[^#[:space:]].*:' Makefile | sed 's/:.*//' | sort | uniq
+
+ifneq ($(TARGETSEARCH),NO)
+ALL_TARGETS := $(shell make list TARGETSEARCH=NO)
+endif
+TEST_TARGETS := $(filter test%,$(ALL_TARGETS))
+.PHONY: $(TEST_TARGETS) # all targets starting by `test` are now .PHONY
+
+test_targets:
+	@echo TEST_TARGETS = $(TEST_TARGETS)
 
 .PHONY: check
 check: test-lz4-essentials
 
-.PHONY: test
 test: test-lz4 test-lz4c test-frametest test-fullbench test-fuzzer test-amalgamation listTest test-decompress-partial
 
-.PHONY: test32
 test32: CFLAGS+=-m32
 test32: test
 
-.PHONY: test-amalgamation
 test-amalgamation: lz4_all.o
 
-lz4_all.c: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c
+CLEAN += lz4_all.c
+lz4_all.c: $(LIBDIR)/lz4.c $(LIBDIR)/lz4hc.c $(LIBDIR)/lz4frame.c
 	$(CAT) $^ > $@
 
-.PHONY: test-install
 test-install: lz4 lib liblz4.pc
 	lz4_root=.. ./test_install.sh
 
-.PHONY: test-compile-with-lz4-memory-usage
 test-compile-with-lz4-memory-usage:
 	$(MAKE) clean; CFLAGS=-O0 CPPFLAGS=-D'LZ4_MEMORY_USAGE=LZ4_MEMORY_USAGE_MIN' $(MAKE) all
 	$(MAKE) clean; CFLAGS=-O0 CPPFLAGS=-D'LZ4_MEMORY_USAGE=LZ4_MEMORY_USAGE_MAX' $(MAKE) all
 
-.PHONY: test-lz4-sparse
 # Rules regarding Temporary test files :
 # Each test must use its own unique set of names during execution.
 # Each temporary test file must begin by an FPREFIX.
@@ -211,312 +221,55 @@
 # All FPREFIX must start with `tmp`, for `make clean`
 # All tests must clean their temporary test files on successful completion,
 # and only their test files : do not employ sweeping statements such `rm tmp*` or `rm *.lz4`
-test-lz4-sparse: FPREFIX = tmp-tls
 test-lz4-sparse: lz4 datagen
 	@echo "\n ---- test sparse file support ----"
-	$(DATAGEN) -g5M  -P100 > $(FPREFIX)dg5M
-	$(LZ4) -B4D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB4
-	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB4
-	$(LZ4) -B5D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB5
-	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB5
-	$(LZ4) -B6D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB6
-	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB6
-	$(LZ4) -B7D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB7
-	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB7
-	$(LZ4) $(FPREFIX)dg5M -c | $(LZ4) -dv --no-sparse > $(FPREFIX)nosparse
-	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)nosparse
-	ls -ls $(FPREFIX)*
-	$(DATAGEN) -s1 -g1200007 -P100 | $(LZ4) | $(LZ4) -dv --sparse > $(FPREFIX)odd   # Odd size file (to generate non-full last block)
-	$(DATAGEN) -s1 -g1200007 -P100 | $(DIFF) -s - $(FPREFIX)odd
-	ls -ls $(FPREFIX)odd
-	@$(RM) $(FPREFIX)*
-	@echo "\n Compatibility with Console :"
-	echo "Hello World 1 !" | $(LZ4) | $(LZ4) -d -c
-	echo "Hello World 2 !" | $(LZ4) | $(LZ4) -d | $(CAT)
-	echo "Hello World 3 !" | $(LZ4) --no-frame-crc | $(LZ4) -d -c
-	@echo "\n Compatibility with Append :"
-	$(DATAGEN) -P100 -g1M > $(FPREFIX)dg1M
-	$(CAT) $(FPREFIX)dg1M $(FPREFIX)dg1M > $(FPREFIX)2M
-	$(LZ4) -B5 -v $(FPREFIX)dg1M $(FPREFIX)c
-	$(LZ4) -d -v $(FPREFIX)c $(FPREFIX)r
-	$(LZ4) -d -v $(FPREFIX)c -c >> $(FPREFIX)r
-	ls -ls $(FPREFIX)*
-	$(DIFF) $(FPREFIX)2M $(FPREFIX)r
-	@$(RM) $(FPREFIX)*
+	./test-lz4-sparse.sh
 
-test-lz4-contentSize: FPREFIX = tmp-lzc
 test-lz4-contentSize: lz4 datagen
 	@echo "\n ---- test original size support ----"
-	$(DATAGEN) -g15M > $(FPREFIX)
-	$(LZ4) -v $(FPREFIX) -c | $(LZ4) -t
-	$(LZ4) -v --content-size $(FPREFIX) -c | $(LZ4) -d > $(FPREFIX)-dup
-	$(DIFF) $(FPREFIX) $(FPREFIX)-dup
-	$(LZ4) -f $(FPREFIX) -c > $(FPREFIX).lz4 # compressed with content size
-	$(LZ4) --content-size $(FPREFIX) -c > $(FPREFIX)-wcz.lz4
-	! $(DIFF) $(FPREFIX).lz4 $(FPREFIX)-wcz.lz4  # must differ, due to content size
-	$(LZ4) --content-size < $(FPREFIX) > $(FPREFIX)-wcz2.lz4 # can determine content size because stdin is just a file
-	$(DIFF) $(FPREFIX)-wcz.lz4 $(FPREFIX)-wcz2.lz4  # both must contain content size
-	$(CAT) $(FPREFIX) | $(LZ4) > $(FPREFIX)-ncz.lz4
-	$(DIFF) $(FPREFIX).lz4 $(FPREFIX)-ncz.lz4  # both don't have content size
-	$(CAT) $(FPREFIX) | $(LZ4) --content-size > $(FPREFIX)-ncz2.lz4 # can't determine content size
-	$(DIFF) $(FPREFIX).lz4 $(FPREFIX)-ncz2.lz4  # both don't have content size
-	@$(RM) $(FPREFIX)*
+	./test-lz4-contentSize.sh
 
-test-lz4-frame-concatenation: FPREFIX = tmp-lfc
 test-lz4-frame-concatenation: lz4 datagen
 	@echo "\n ---- test frame concatenation ----"
-	@echo -n > $(FPREFIX)-empty
-	@echo hi > $(FPREFIX)-nonempty
-	$(CAT) $(FPREFIX)-nonempty $(FPREFIX)-empty $(FPREFIX)-nonempty > $(FPREFIX)-src
-	$(LZ4) -zq $(FPREFIX)-empty -c > $(FPREFIX)-empty.lz4
-	$(LZ4) -zq $(FPREFIX)-nonempty -c > $(FPREFIX)-nonempty.lz4
-	$(CAT) $(FPREFIX)-nonempty.lz4 $(FPREFIX)-empty.lz4 $(FPREFIX)-nonempty.lz4 > $(FPREFIX)-concat.lz4
-	$(LZ4) -d $(FPREFIX)-concat.lz4 -c > $(FPREFIX)-result
-	$(CMP) $(FPREFIX)-src $(FPREFIX)-result
-	@$(RM) $(FPREFIX)*
-	@echo frame concatenation test completed
+	./test-lz4-frame-concatenation.sh
 
-test-lz4-multiple: FPREFIX = tmp-tml
 test-lz4-multiple: lz4 datagen
 	@echo "\n ---- test multiple files ----"
-	@$(DATAGEN) -s1        > $(FPREFIX)1 2> $(VOID)
-	@$(DATAGEN) -s2 -g100K > $(FPREFIX)2 2> $(VOID)
-	@$(DATAGEN) -s3 -g200K > $(FPREFIX)3 2> $(VOID)
-	# compress multiple files : one .lz4 per source file
-	$(LZ4) -f -m $(FPREFIX)*
-	test -f $(FPREFIX)1.lz4
-	test -f $(FPREFIX)2.lz4
-	test -f $(FPREFIX)3.lz4
-	# decompress multiple files : one output file per .lz4
-	mv $(FPREFIX)1 $(FPREFIX)1-orig
-	mv $(FPREFIX)2 $(FPREFIX)2-orig
-	mv $(FPREFIX)3 $(FPREFIX)3-orig
-	$(LZ4) -d -f -m $(FPREFIX)*.lz4
-	$(CMP) $(FPREFIX)1 $(FPREFIX)1-orig   # must be identical
-	$(CMP) $(FPREFIX)2 $(FPREFIX)2-orig
-	$(CMP) $(FPREFIX)3 $(FPREFIX)3-orig
-	# compress multiple files into stdout
-	$(CAT) $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 > $(FPREFIX)-concat1
-	$(RM) $(FPREFIX)*.lz4
-	$(LZ4) -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 -c > $(FPREFIX)-concat2
-	test ! -f $(FPREFIX)1.lz4  # must not create .lz4 artefact
-	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
-	# decompress multiple files into stdout
-	$(RM) $(FPREFIX)-concat1 $(FPREFIX)-concat2
-	$(LZ4) -f -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3   # generate .lz4 to decompress
-	$(CAT) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 > $(FPREFIX)-concat1   # create concatenated reference
-	$(RM) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3
-	$(LZ4) -d -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2
-	test ! -f $(FPREFIX)1  # must not create file artefact
-	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
-	# compress multiple files, one of which is absent (must fail)
-	! $(LZ4) -f -m $(FPREFIX)-concat1 notHere $(FPREFIX)-concat2  # must fail : notHere not present
-	# test lz4-compressed file
-	$(LZ4) -tm $(FPREFIX)-concat1.lz4
-	$(LZ4) -tm $(FPREFIX)-concat1.lz4 $(FPREFIX)-concat2.lz4
-	# test multiple lz4 files, one of which is absent (must fail)
-	! $(LZ4) -tm $(FPREFIX)-concat1.lz4 notHere.lz4 $(FPREFIX)-concat2.lz4
-	@$(RM) $(FPREFIX)*
+	./test-lz4-multiple.sh
 
-test-lz4-multiple-legacy: FPREFIX = tmp-lml
 test-lz4-multiple-legacy: lz4 datagen
 	@echo "\n ---- test multiple files (Legacy format) ----"
-	@$(DATAGEN) -s1        > $(FPREFIX)1 2> $(VOID)
-	@$(DATAGEN) -s2 -g100K > $(FPREFIX)2 2> $(VOID)
-	@$(DATAGEN) -s3 -g200K > $(FPREFIX)3 2> $(VOID)
-	# compress multiple files using legacy format: one .lz4 per source file
-	$(LZ4) -f -l -m $(FPREFIX)*
-	test -f $(FPREFIX)1.lz4
-	test -f $(FPREFIX)2.lz4
-	test -f $(FPREFIX)3.lz4
-	# decompress multiple files compressed using legacy format: one output file per .lz4
-	mv $(FPREFIX)1 $(FPREFIX)1-orig
-	mv $(FPREFIX)2 $(FPREFIX)2-orig
-	mv $(FPREFIX)3 $(FPREFIX)3-orig
-	$(LZ4) -d -f -m $(FPREFIX)*.lz4
-	$(LZ4) -l -d -f -m $(FPREFIX)*.lz4 # -l mustn't impact -d option
-	$(CMP) $(FPREFIX)1 $(FPREFIX)1-orig   # must be identical
-	$(CMP) $(FPREFIX)2 $(FPREFIX)2-orig
-	$(CMP) $(FPREFIX)3 $(FPREFIX)3-orig
-	# compress multiple files into stdout using legacy format
-	$(CAT) $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 > $(FPREFIX)-concat1
-	$(RM) $(FPREFIX)*.lz4
-	$(LZ4) -l -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 -c > $(FPREFIX)-concat2
-	test ! -f $(FPREFIX)1.lz4  # must not create .lz4 artefact
-	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
-	# # # decompress multiple files into stdout using legacy format
-	$(RM) $(FPREFIX)-concat1 $(FPREFIX)-concat2
-	$(LZ4) -l -f -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3   # generate .lz4 to decompress
-	$(CAT) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 > $(FPREFIX)-concat1   # create concatenated reference
-	$(RM) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3
-	$(LZ4) -d -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2
-	$(LZ4) -d -l -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2 # -l mustn't impact option -d
-	test ! -f $(FPREFIX)1  # must not create file artefact
-	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
-	# # # compress multiple files, one of which is absent (must fail)
-	! $(LZ4) -f -l -m $(FPREFIX)-concat1 notHere-legacy $(FPREFIX)-concat2  # must fail : notHere-legacy not present
-	@$(RM) $(FPREFIX)*
+	./test-lz4-multiple-legacy.sh
 
-SKIPFILE = goldenSamples/skip.bin
-test-lz4-skippable: FPREFIX = tmp-lsk
-test-lz4-skippable: lz4 datagen
+test-lz4-skippable: lz4
 	@echo "\n ---- test lz4 with skippable frames ----"
-	$(LZ4) -dc $(SKIPFILE)
-	$(LZ4) -dc < $(SKIPFILE)
-	cat $(SKIPFILE) | $(LZ4) -dc
-	echo "Hello from Valid Frame!\n" | $(LZ4) -c > $(FPREFIX).lz4
-	cat $(SKIPFILE) $(FPREFIX).lz4 $(SKIPFILE) | $(LZ4) -dc
-	$(RM) $(FPREFIX)*
+	./test-lz4-skippable.sh
 
-test-lz4-basic: FPREFIX = tmp-tlb
 test-lz4-basic: lz4 datagen unlz4 lz4cat
 	@echo "\n ---- test lz4 basic compression/decompression ----"
-	$(DATAGEN) -g0       | $(LZ4) -v     | $(LZ4) -t
-	$(DATAGEN) -g16KB    | $(LZ4) -9     | $(LZ4) -t
-	$(DATAGEN) -g20KB > $(FPREFIX)-dg20k
-	$(LZ4) < $(FPREFIX)-dg20k | $(LZ4) -d > $(FPREFIX)-dec
-	$(DIFF) -q $(FPREFIX)-dg20k $(FPREFIX)-dec
-	$(LZ4) --no-frame-crc < $(FPREFIX)-dg20k | $(LZ4) -d > $(FPREFIX)-dec
-	$(DIFF) -q $(FPREFIX)-dg20k $(FPREFIX)-dec
-	$(DATAGEN)           | $(LZ4) -BI    | $(LZ4) -t
-	$(DATAGEN)           | $(LZ4) --no-crc | $(LZ4) -t
-	$(DATAGEN) -g6M -P99 | $(LZ4) -9BD   | $(LZ4) -t
-	$(DATAGEN) -g17M     | $(LZ4) -9v    | $(LZ4) -qt
-	$(DATAGEN) -g33M     | $(LZ4) --no-frame-crc | $(LZ4) -t
-	$(DATAGEN) -g256MB   | $(LZ4) -vqB4D | $(LZ4) -t --no-crc
-	@echo "hello world" > $(FPREFIX)-hw
-	$(LZ4) --rm -f $(FPREFIX)-hw $(FPREFIX)-hw.lz4
-	test ! -f $(FPREFIX)-hw                      # must fail (--rm)
-	test   -f $(FPREFIX)-hw.lz4
-	$(PRGDIR)/lz4cat $(FPREFIX)-hw.lz4 | $(GREP) "hello world"
-	$(PRGDIR)/unlz4 --rm $(FPREFIX)-hw.lz4 $(FPREFIX)-hw
-	test   -f $(FPREFIX)-hw
-	test ! -f $(FPREFIX)-hw.lz4                  # must fail (--rm)
-	test ! -f $(FPREFIX)-hw.lz4.lz4              # must fail (unlz4)
-	$(PRGDIR)/lz4cat $(FPREFIX)-hw               # pass-through mode
-	test   -f $(FPREFIX)-hw
-	test ! -f $(FPREFIX)-hw.lz4                  # must fail (lz4cat)
-	$(LZ4) $(FPREFIX)-hw $(FPREFIX)-hw.lz4          # creates $(FPREFIX)-hw.lz4
-	$(PRGDIR)/lz4cat < $(FPREFIX)-hw.lz4 > $(FPREFIX)3  # checks lz4cat works with stdin (#285)
-	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)3
-	$(PRGDIR)/lz4cat < $(FPREFIX)-hw > $(FPREFIX)2      # checks lz4cat works in pass-through mode
-	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)2
-	cp $(FPREFIX)-hw ./-d
-	$(LZ4) --rm -- -d -d.lz4               # compresses ./d into ./-d.lz4
-	test   -f ./-d.lz4
-	test ! -f ./-d
-	mv ./-d.lz4 ./-z
-	$(LZ4) -d --rm -- -z $(FPREFIX)4          # uncompresses ./-z into $(FPREFIX)4
-	test ! -f ./-z
-	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)4
-	! $(LZ4) $(FPREFIX)2 $(FPREFIX)3 $(FPREFIX)4    # must fail: refuse to handle 3+ file names
-	$(LZ4) -f $(FPREFIX)-hw                   # create $(FPREFIX)-hw.lz4, for next tests
-	$(LZ4) --list $(FPREFIX)-hw.lz4           # test --list on valid single-frame file
-	$(LZ4) --list < $(FPREFIX)-hw.lz4         # test --list from stdin (file only)
-	$(CAT) $(FPREFIX)-hw >> $(FPREFIX)-hw.lz4
-	! $(LZ4) -f $(FPREFIX)-hw.lz4             # uncompress valid frame followed by invalid data (must fail now)
-	$(LZ4) -BX $(FPREFIX)-hw -c -q | $(LZ4) -tv  # test block checksum
-	# $(DATAGEN) -g20KB generates the same file every single time
-	# cannot save output of $(DATAGEN) -g20KB as input file to lz4 because the following shell commands are run before $(DATAGEN) -g20KB
-	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast | wc -c)" -lt "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast=9 | wc -c)" # -1 vs -9
-	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c -1 | wc -c)" -lt "$(shell $(DATAGEN) -g20KB| $(LZ4) -c --fast=1 | wc -c)" # 1 vs -1
-	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast=1 | wc -c)" -eq "$(shell $(DATAGEN) -g20KB| $(LZ4) -c --fast| wc -c)" # checks default fast compression is -1
-	! $(LZ4) -c --fast=0 $(FPREFIX)-dg20K # lz4 should fail when fast=0
-	! $(LZ4) -c --fast=-1 $(FPREFIX)-dg20K # lz4 should fail when fast=-1
-	# High --fast values can result in out-of-bound dereferences #876
-	$(DATAGEN) -g1M | $(LZ4) -c --fast=999999999 > /dev/null
-	# Test for #596
-	@echo "TEST" > $(FPREFIX)-test
-	$(LZ4) -m $(FPREFIX)-test
-	$(LZ4) $(FPREFIX)-test.lz4 $(FPREFIX)-test2
-	$(DIFF) -q $(FPREFIX)-test $(FPREFIX)-test2
-	@$(RM) $(FPREFIX)*
+	./test-lz4-basic.sh
 
-
-test-lz4-dict: FPREFIX = tmp-dict
 test-lz4-dict: lz4 datagen
 	@echo "\n ---- test lz4 compression/decompression with dictionary ----"
-	$(DATAGEN) -g16KB > $(FPREFIX)
-	$(DATAGEN) -g32KB > $(FPREFIX)-sample-32k
-	< $(FPREFIX)-sample-32k $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-32k
-	$(DATAGEN) -g128MB > $(FPREFIX)-sample-128m
-	< $(FPREFIX)-sample-128m $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-128m
-	touch $(FPREFIX)-sample-0
-	< $(FPREFIX)-sample-0 $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-0
-
-	< $(FPREFIX)-sample-32k $(LZ4) -D $(FPREFIX)-sample-0 | $(LZ4) -dD $(FPREFIX)-sample-0 | diff - $(FPREFIX)-sample-32k
-	< $(FPREFIX)-sample-0 $(LZ4) -D $(FPREFIX)-sample-0 | $(LZ4) -dD $(FPREFIX)-sample-0 | diff - $(FPREFIX)-sample-0
-
-	@echo "\n ---- test lz4 dictionary loading ----"
-	$(DATAGEN) -g128KB > $(FPREFIX)-data-128KB
-	set -e; \
-	for l in 0 1 4 128 32767 32768 32769 65535 65536 65537 98303 98304 98305 131071 131072 131073; do \
-		$(DATAGEN) -g$$l > $(FPREFIX)-$$l; \
-		$(DD) if=$(FPREFIX)-$$l of=$(FPREFIX)-$$l-tail bs=1 count=65536 skip=$$((l > 65536 ? l - 65536 : 0)); \
-		< $(FPREFIX)-$$l      $(LZ4) -D stdin $(FPREFIX)-data-128KB -c | $(LZ4) -dD $(FPREFIX)-$$l-tail | $(DIFF) - $(FPREFIX)-data-128KB; \
-		< $(FPREFIX)-$$l-tail $(LZ4) -D stdin $(FPREFIX)-data-128KB -c | $(LZ4) -dD $(FPREFIX)-$$l      | $(DIFF) - $(FPREFIX)-data-128KB; \
-	done
-	@$(RM) $(FPREFIX)*
+	./test-lz4-dict.sh
 
 test-lz4hc-hugefile: lz4 datagen
 	@echo "\n ---- test HC compression/decompression of huge files ----"
-	$(DATAGEN) -g4200MB | $(LZ4) -v3BD | $(LZ4) -qt
+	./test-lz4hc-hugefile.sh
 
-test-lz4-fast-hugefile: FPREFIX = tmp-lfh
 test-lz4-fast-hugefile: lz4 datagen
 	@echo "\n ---- test huge files compression/decompression ----"
-	$(DATAGEN) -g6GB    | $(LZ4) -vB5D | $(LZ4) -qt
-	# test large file size [2-4] GB
-	@$(DATAGEN) -g3G -P100 | $(LZ4) -vv | $(LZ4) --decompress --force --sparse - $(FPREFIX)1
-	@ls -ls $(FPREFIX)1
-	@$(DATAGEN) -g3G -P100 | $(LZ4) --quiet --content-size | $(LZ4) --verbose --decompress --force --sparse - $(FPREFIX)2
-	@ls -ls $(FPREFIX)2
-	$(DIFF) -s $(FPREFIX)1 $(FPREFIX)2
-	@$(RM) $(FPREFIX)*
+	./test-lz4-fast-hugefile.sh
 
 test-lz4-hugefile: test-lz4-fast-hugefile test-lz4hc-hugefile
 
-test-lz4-testmode: FPREFIX = tmp-ltm
 test-lz4-testmode: lz4 datagen
 	@echo "\n ---- bench mode ----"
-	$(LZ4) -bi0
-	$(DATAGEN) > $(FPREFIX)
-	$(LZ4) -f $(FPREFIX) -c > $(FPREFIX).lz4
-	$(LZ4) -bdi0 $(FPREFIX).lz4 # test benchmark decode-only mode
-	$(LZ4) -bdi0 --no-crc $(FPREFIX).lz4 # test benchmark decode-only mode
-	@echo "\n ---- test mode ----"
-	! $(DATAGEN) | $(LZ4) -t
-	! $(DATAGEN) | $(LZ4) -tf
-	@echo "\n ---- pass-through mode ----"
-	@echo "Why hello there " > $(FPREFIX)2.lz4
-	! $(LZ4) -f $(FPREFIX)2.lz4 > $(VOID)
-	! $(DATAGEN) | $(LZ4) -dc  > $(VOID)
-	! $(DATAGEN) | $(LZ4) -df > $(VOID)
-	$(DATAGEN) | $(LZ4) -dcf > $(VOID)
-	@echo "Hello World !" > $(FPREFIX)1
-	$(LZ4) -dcf $(FPREFIX)1
-	@echo "from underground..." > $(FPREFIX)2
-	$(LZ4) -dcfm $(FPREFIX)1 $(FPREFIX)2
-	@echo "\n ---- non-existing source (must fail cleanly) ----"
-	! $(LZ4)     file-does-not-exist
-	! $(LZ4) -f  file-does-not-exist
-	! $(LZ4) -t  file-does-not-exist
-	! $(LZ4) -fm file1-dne file2-dne
-	@$(RM) $(FPREFIX)*
+	./test-lz4-testmode.sh
 
 test-lz4-opt-parser: lz4 datagen
 	@echo "\n ---- test opt-parser ----"
-	$(DATAGEN) -g16KB      | $(LZ4) -12      | $(LZ4) -t
-	$(DATAGEN) -P10        | $(LZ4) -12B4    | $(LZ4) -t
-	$(DATAGEN) -g256K      | $(LZ4) -12B4D   | $(LZ4) -t
-	$(DATAGEN) -g512K -P25 | $(LZ4) -12BD    | $(LZ4) -t
-	$(DATAGEN) -g1M        | $(LZ4) -12B5    | $(LZ4) -t
-	$(DATAGEN) -g1M -s2    | $(LZ4) -12B4D   | $(LZ4) -t
-	$(DATAGEN) -g2M -P99   | $(LZ4) -11B4D   | $(LZ4) -t
-	$(DATAGEN) -g4M        | $(LZ4) -11vq    | $(LZ4) -qt
-	$(DATAGEN) -g8M        | $(LZ4) -11B4    | $(LZ4) -t
-	$(DATAGEN) -g16M -P90  | $(LZ4) -11B5    | $(LZ4) -t
-	$(DATAGEN) -g32M -P10  | $(LZ4) -11B5D   | $(LZ4) -t
+	./test-lz4-opt-parser.sh
 
 test-lz4-essentials : lz4 datagen test-lz4-basic test-lz4-multiple test-lz4-multiple-legacy \
                       test-lz4-frame-concatenation test-lz4-testmode \
@@ -609,10 +362,36 @@
 	@echo "\n ---- test decompress-partial-usingDict ----"
 	./decompress-partial-usingDict$(EXT)
 
+
+#-----------------------------------------------------------------------------
+# freestanding test only for Linux x86_64
+#-----------------------------------------------------------------------------
+UNAME_S ?= $(if $(filter Windows_NT,$(OS)),Windows,$(shell uname -s))
+UNAME_P ?= $(if $(filter Windows_NT,$(OS)),Unknown,$(shell uname -p))
+
+FREESTANDING_CFLAGS := -ffreestanding -nostdlib
+
+ifneq ($(UNAME_S), Linux)
+  FREESTANDING_CFLAGS :=
+endif
+
+ifneq ($(UNAME_P), x86_64)
+  FREESTANDING_CFLAGS :=
+endif
+
+CLEAN += freestanding
+freestanding: freestanding.c
+	$(CC) $(FREESTANDING_CFLAGS) $^ -o $@$(EXT)
+
 test-freestanding: freestanding
 	@echo "\n ---- test freestanding ----"
+ifeq ($(FREESTANDING_CFLAGS),)
+	@echo "\n (skip)"
+else
 	./freestanding$(EXT)
 	-strace ./freestanding$(EXT)
 	-ltrace ./freestanding$(EXT)
+endif
+
 
 endif
diff --git a/tests/checkFrame.c b/tests/checkFrame.c
index 946805f..f083520 100644
--- a/tests/checkFrame.c
+++ b/tests/checkFrame.c
@@ -1,76 +1,85 @@
-  /*
-      checkFrame - verify frame headers
-      Copyright (C) Yann Collet 2014-2020
+/*
+    checkFrame - verify frame headers
+    Copyright (C) Yann Collet 2014-2020
 
-      GPL v2 License
+    GPL v2 License
 
-      This program is free software; you can redistribute it and/or modify
-      it under the terms of the GNU General Public License as published by
-      the Free Software Foundation; either version 2 of the License, or
-      (at your option) any later version.
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
 
-      This program is distributed in the hope that it will be useful,
-      but WITHOUT ANY WARRANTY; without even the implied warranty of
-      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-      GNU General Public License for more details.
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
 
-      You should have received a copy of the GNU General Public License along
-      with this program; if not, write to the Free Software Foundation, Inc.,
-      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-      You can contact the author at :
-      - LZ4 homepage : http://www.lz4.org
-      - LZ4 source repository : https://github.com/lz4/lz4
-  */
-
-  /*-************************************
-  *  Includes
-  **************************************/
-  #include "util.h"       /* U32 */
-  #include <stdlib.h>     /* malloc, free */
-  #include <stdio.h>      /* fprintf */
-  #include <string.h>     /* strcmp */
-  #include <time.h>       /* clock_t, clock(), CLOCKS_PER_SEC */
-  #include <assert.h>
-  #include "lz4frame.h"   /* include multiple times to test correctness/safety */
-  #include "lz4frame.h"
-  #define LZ4F_STATIC_LINKING_ONLY
-  #include "lz4frame.h"
-  #include "lz4frame.h"
-  #include "lz4.h"        /* LZ4_VERSION_STRING */
-  #define XXH_STATIC_LINKING_ONLY
-  #include "xxhash.h"     /* XXH64 */
+    You can contact the author at :
+    - LZ4 homepage : http://www.lz4.org
+    - LZ4 source repository : https://github.com/lz4/lz4
+*/
 
 
-  /*-************************************
-  *  Constants
-  **************************************/
-  #define KB *(1U<<10)
-  #define MB *(1U<<20)
-  #define GB *(1U<<30)
+/*-************************************
+*  Compiler options
+**************************************/
+#ifdef _MSC_VER    /* Visual Studio */
+#  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
+#endif
 
 
-  /*-************************************
-  *  Macros
-  **************************************/
-  #define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
-  #define DISPLAYLEVEL(l, ...)  if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+/*-************************************
+*  Includes
+**************************************/
+#include "util.h"       /* U32 */
+#include <stdlib.h>     /* malloc, free */
+#include <stdio.h>      /* fprintf */
+#include <string.h>     /* strcmp */
+#include <time.h>       /* clock_t, clock(), CLOCKS_PER_SEC */
+#include <assert.h>
+#include "lz4frame.h"   /* include multiple times to test correctness/safety */
+#include "lz4frame.h"
+#define LZ4F_STATIC_LINKING_ONLY
+#include "lz4frame.h"
+#include "lz4frame.h"
+#include "lz4.h"        /* LZ4_VERSION_STRING */
+#define XXH_STATIC_LINKING_ONLY
+#include "xxhash.h"     /* XXH64 */
 
-  /**************************************
-  *  Exceptions
-  ***************************************/
-  #ifndef DEBUG
-  #  define DEBUG 0
-  #endif
-  #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
-  #define EXM_THROW(error, ...)                                             \
-{                                                                         \
+
+/*-************************************
+*  Constants
+**************************************/
+#define KB *(1U<<10)
+#define MB *(1U<<20)
+#define GB *(1U<<30)
+
+
+/*-************************************
+*  Macros
+**************************************/
+#define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
+#define DISPLAYLEVEL(l, ...)  if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+
+/**************************************
+*  Exceptions
+***************************************/
+#ifndef DEBUG
+#  define DEBUG 0
+#endif
+#define DEBUGOUTPUT(...) do { if (DEBUG) DISPLAY(__VA_ARGS__); } while (0)
+#define EXM_THROW(error, ...)                                           \
+do {                                                                      \
     DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
     DISPLAYLEVEL(1, "Error %i : ", error);                                \
     DISPLAYLEVEL(1, __VA_ARGS__);                                         \
     DISPLAYLEVEL(1, " \n");                                               \
-    return(error);                                                          \
-}
+    return(error);                                                        \
+} while (0)
 
 
 
diff --git a/tests/cmake/CMakeLists.txt b/tests/cmake/CMakeLists.txt
new file mode 100644
index 0000000..7077724
--- /dev/null
+++ b/tests/cmake/CMakeLists.txt
@@ -0,0 +1,28 @@
+cmake_minimum_required(VERSION 3.5)
+
+project(cmake_install_test LANGUAGES C)
+
+# Find LZ4 installation in Config mode
+find_package(lz4 CONFIG REQUIRED)
+
+# Verify that the universal target always exists
+if (NOT TARGET LZ4::lz4)
+  message(FATAL_ERROR "LZ4::lz4 target does not exist!")
+endif()
+
+# Verify that the location property is set
+get_property(LZ4_LOCATION TARGET LZ4::lz4_shared PROPERTY LOCATION)
+if (NOT LZ4_LOCATION)
+  message(FATAL_ERROR "Missing LOCATION property for LZ4::lz4_shared!")
+endif()
+
+# Verify that the include directory property is set
+get_property(LZ4_SHARED_INCLUDE_DIRECTORIES TARGET LZ4::lz4_shared PROPERTY INTERFACE_INCLUDE_DIRECTORIES)
+if (NOT LZ4_SHARED_INCLUDE_DIRECTORIES)
+  message(FATAL_ERROR "Missing INTERFACE_INCLUDE_DIRECTORIES property for LZ4::lz4_shared!")
+endif()
+
+# Add a test that builds against the installation
+set(LZ4_TESTS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/..")
+add_executable(decompress-partial "${LZ4_TESTS_SOURCE_DIR}/decompress-partial.c")
+target_link_libraries(decompress-partial LZ4::lz4_shared)
diff --git a/programs/datagen.c b/tests/datagen.c
similarity index 98%
rename from programs/datagen.c
rename to tests/datagen.c
index f448640..4b5039a 100644
--- a/programs/datagen.c
+++ b/tests/datagen.c
@@ -1,6 +1,6 @@
 /*
     datagen.c - compressible data generator test tool
-    Copyright (C) Yann Collet 2012-2020
+    Copyright (C) Yann Collet 2012-2024
 
     GPL v2 License
 
@@ -52,7 +52,6 @@
 typedef BYTE litDistribTable[LTSIZE];
 
 
-
 /*********************************************************
 *  Local Functions
 *********************************************************/
@@ -133,7 +132,7 @@
             /* Copy (within 32K) */
             size_t match;
             size_t d;
-            int length = RDG_RANDLENGTH + 4;
+            size_t length = RDG_RANDLENGTH + 4;
             U32 offset = RDG_RAND15BITS + 1;
             if (offset > pos) offset = (U32)pos;
             match = pos - offset;
diff --git a/programs/datagen.h b/tests/datagen.h
similarity index 71%
rename from programs/datagen.h
rename to tests/datagen.h
index c20c9c7..4d73c40 100644
--- a/programs/datagen.h
+++ b/tests/datagen.h
@@ -1,6 +1,6 @@
 /*
     datagen.h - compressible data generator header
-    Copyright (C) Yann Collet 2012-2020
+    Copyright (C) Yann Collet 2012-2024
 
     GPL v2 License
 
@@ -26,15 +26,17 @@
 
 #include <stddef.h>   /* size_t */
 
+/* RDG_genOut():
+ * Generate @size bytes of compressible data into stdout.
+ * Compressibility can be controlled using @matchProba.
+ * @LitProba is optional, and affect variability of bytes. If @litProba==0.0, default value is used.
+ * Generated data can be influenced using @seed.
+ * If @matchProba, @litProba and @seed are equal, the function always generates the same content.
+ */
 void RDG_genOut(unsigned long long size, double matchProba, double litProba, unsigned seed);
-void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed);
-/* RDG_genOut
-   Generate 'size' bytes of compressible data into stdout.
-   Compressibility can be controlled using 'matchProba'.
-   'LitProba' is optional, and affect variability of bytes. If litProba==0.0, default value is used.
-   Generated data can be selected using 'seed'.
-   If (matchProba, litProba and seed) are equal, the function always generate the same content.
 
-   RDG_genBuffer
-   Same as RDG_genOut, but generate data into provided buffer
-*/
+/*
+ * RDG_genBuffer():
+ * Same as RDG_genOut, but generates data into provided @buffer
+ */
+void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed);
diff --git a/tests/datagencli.c b/tests/datagencli.c
index ccb27df..6990043 100644
--- a/tests/datagencli.c
+++ b/tests/datagencli.c
@@ -24,12 +24,14 @@
    - Public forum : https://groups.google.com/forum/#!forum/lz4c
 */
 
+
 /**************************************
 *  Includes
 **************************************/
 #include "util.h"      /* U32 */
 #include <stdio.h>     /* fprintf, stderr */
 #include "datagen.h"   /* RDG_generate */
+#include "loremOut.h"  /* LOREM_genOut */
 #include "lz4.h"       /* LZ4_VERSION_STRING */
 
 
@@ -37,7 +39,8 @@
 *  Compiler specific
 **************************************/
 #ifdef _MSC_VER    /* Visual Studio */
-#define strtoull    _strtoui64  /* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtoui64-wcstoui64-strtoui64-l-wcstoui64-l */
+# pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
+# define strtoull  _strtoui64  /* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtoui64-wcstoui64-strtoui64-l-wcstoui64-l */
 #endif
 
 
@@ -50,14 +53,14 @@
 
 #define SIZE_DEFAULT (64 KB)
 #define SEED_DEFAULT 0
-#define COMPRESSIBILITY_DEFAULT 50
+#define COMPRESSIBILITY_NOT_SET 9999
 
 
 /**************************************
 *  Macros
 **************************************/
 #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYLEVEL(l, ...) do { if (displayLevel>=(l)) DISPLAY(__VA_ARGS__); } while (0)
 static unsigned displayLevel = 2;
 
 
@@ -73,7 +76,7 @@
     DISPLAY( "Arguments :\n");
     DISPLAY( " -g#    : generate # data (default:%i)\n", SIZE_DEFAULT);
     DISPLAY( " -s#    : Select seed (default:%i)\n", SEED_DEFAULT);
-    DISPLAY( " -P#    : Select compressibility in %% (default:%i%%)\n", COMPRESSIBILITY_DEFAULT);
+    DISPLAY( " -P#    : Select compressibility in %% (range [0-100])\n");
     DISPLAY( " -h     : display help and exit\n");
     DISPLAY( "Special values :\n");
     DISPLAY( " -P0    : generate incompressible noise\n");
@@ -85,28 +88,24 @@
 int main(int argc, char** argv)
 {
     int argNb;
-    double proba = (double)COMPRESSIBILITY_DEFAULT / 100;
+    unsigned long long proba = COMPRESSIBILITY_NOT_SET;
     double litProba = 0.0;
     U64 size = SIZE_DEFAULT;
-    U32 seed = SEED_DEFAULT;
+    unsigned seed = SEED_DEFAULT;
     char* programName;
 
     /* Check command line */
     programName = argv[0];
-    for(argNb=1; argNb<argc; argNb++)
-    {
+    for(argNb=1; argNb<argc; argNb++) {
         char* argument = argv[argNb];
 
         if(!argument) continue;   /* Protection if argument empty */
 
         /* Handle commands. Aggregated commands are allowed */
-        if (*argument=='-')
-        {
+        if (*argument=='-') {
             argument++;
-            while (*argument!=0)
-            {
-                switch(*argument)
-                {
+            while (*argument!=0) {
+                switch(*argument) {
                 case 'h':
                     return usage(programName);
                 case 'g':
@@ -119,12 +118,11 @@
                     break;
                 case 's':
                     argument++;
-                    seed = (U32) strtoul(argument, &argument, 10);
+                    seed = (unsigned)strtoul(argument, &argument, 10);
                     break;
                 case 'P':
                     argument++;
-                    proba = (double) strtoull(argument, &argument, 10);
-                    proba /= 100.;
+                    proba = strtoull(argument, &argument, 10);
                     break;
                 case 'L':   /* hidden argument : Literal distribution probability */
                     argument++;
@@ -140,15 +138,17 @@
                     return usage(programName);
                 }
             }
-
-        }
-    }
+        }  /* if (*argument=='-') */
+    }  /* for(argNb=1; argNb<argc; argNb++) */
 
     DISPLAYLEVEL(4, "Data Generator %s \n", LZ4_VERSION_STRING);
     DISPLAYLEVEL(3, "Seed = %u \n", seed);
-    if (proba!=COMPRESSIBILITY_DEFAULT) DISPLAYLEVEL(3, "Compressibility : %i%%\n", (U32)(proba*100));
-
-    RDG_genOut(size, proba, litProba, seed);
+    if (proba != COMPRESSIBILITY_NOT_SET) {
+        DISPLAYLEVEL(3, "Compressibility : %i%%\n", (int)proba);
+        RDG_genOut(size, (double)proba / 100., litProba, seed);
+    } else {
+        LOREM_genOut(size, seed);
+    }
     DISPLAYLEVEL(1, "\n");
 
     return 0;
diff --git a/tests/decompress-partial.c b/tests/decompress-partial.c
index 4e124b7..4385f76 100644
--- a/tests/decompress-partial.c
+++ b/tests/decompress-partial.c
@@ -33,7 +33,7 @@
   char outBuffer[BUFFER_SIZE];
   int cmpSize;
   int i;
-  
+
   cmpSize = LZ4_compress_default(source, cmpBuffer, srcLen, BUFFER_SIZE);
 
   for (i = cmpSize; i < cmpSize + 10; ++i) {
@@ -43,7 +43,7 @@
       return -1;
     }
   }
-  
+
   printf("test decompress-partial OK \n");
   return 0;
 }
diff --git a/tests/frametest.c b/tests/frametest.c
index 3301955..74992bc 100644
--- a/tests/frametest.c
+++ b/tests/frametest.c
@@ -28,6 +28,7 @@
 **************************************/
 #ifdef _MSC_VER    /* Visual Studio */
 #  pragma warning(disable : 26451)     /* disable: Arithmetic overflow */
+#  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
 #endif
 
 
@@ -79,11 +80,11 @@
 *  Macros
 **************************************/
 #define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...)  if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
-#define DISPLAYUPDATE(l, ...) if (displayLevel>=l) { \
+#define DISPLAYLEVEL(l, ...)  do { if (displayLevel>=(l)) DISPLAY(__VA_ARGS__); } while (0)
+#define DISPLAYUPDATE(l, ...) do { if (displayLevel>=(l)) { \
             if ((FUZ_GetClockSpan(g_clockTime) > refreshRate) || (displayLevel>=4)) \
             { g_clockTime = clock(); DISPLAY(__VA_ARGS__); \
-            if (displayLevel>=4) fflush(stdout); } }
+            if (displayLevel>=4) fflush(stdout); } } } while (0)
 static const clock_t refreshRate = CLOCKS_PER_SEC / 6;
 static clock_t g_clockTime = 0;
 
@@ -114,7 +115,7 @@
     if (p==NULL) return NULL;
     assert(t != NULL);
     t->nbAllocs += 1;
-    DISPLAYLEVEL(6, "Allocating %zu bytes at address %p \n", s, p);
+    DISPLAYLEVEL(6, "Allocating %u bytes at address %p \n", (unsigned)s, p);
     DISPLAYLEVEL(5, "nb allocated memory segments : %i \n", t->nbAllocs);
     return p;
 }
@@ -126,7 +127,7 @@
     if (p==NULL) return NULL;
     assert(t != NULL);
     t->nbAllocs += 1;
-    DISPLAYLEVEL(6, "Allocating and zeroing %zu bytes at address %p \n", s, p);
+    DISPLAYLEVEL(6, "Allocating and zeroing %u bytes at address %p \n", (unsigned)s, p);
     DISPLAYLEVEL(5, "nb allocated memory segments : %i \n", t->nbAllocs);
     return p;
 }
@@ -170,38 +171,38 @@
     return rand32 >> 5;
 }
 
-#define FUZ_RAND15BITS  (FUZ_rand(seed) & 0x7FFF)
-#define FUZ_RANDLENGTH  ( (FUZ_rand(seed) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15)
-static void FUZ_fillCompressibleNoiseBuffer(void* buffer, size_t bufferSize, double proba, U32* seed)
+#define RAND_BITS(N) (FUZ_rand(randState) & ((1 << (N))-1))
+#define FUZ_LITERAL (RAND_BITS(6) + '0')
+#define FUZ_ABOUT(_R) ((FUZ_rand(randState) % (_R)) + (FUZ_rand(randState) % (_R)) + 1)
+static void FUZ_fillCompressibleNoiseBuffer(void* buffer, size_t bufferSize, double proba, U32* randState)
 {
     BYTE* BBuffer = (BYTE*)buffer;
     size_t pos = 0;
     U32 P32 = (U32)(32768 * proba);
 
     /* First Byte */
-    BBuffer[pos++] = (BYTE)(FUZ_rand(seed));
+    BBuffer[pos++] = FUZ_LITERAL;
 
     while (pos < bufferSize) {
         /* Select : Literal (noise) or copy (within 64K) */
-        if (FUZ_RAND15BITS < P32) {
+        if (RAND_BITS(15) < P32) {
             /* Copy (within 64K) */
-            size_t const lengthRand = FUZ_RANDLENGTH + 4;
+            size_t const lengthRand = FUZ_ABOUT(8) + 4;
             size_t const length = MIN(lengthRand, bufferSize - pos);
             size_t const end = pos + length;
-            size_t const offsetRand = FUZ_RAND15BITS + 1;
+            size_t const offsetRand = RAND_BITS(15) + 1;
             size_t const offset = MIN(offsetRand, pos);
             size_t match = pos - offset;
             while (pos < end) BBuffer[pos++] = BBuffer[match++];
         } else {
             /* Literal (noise) */
-            size_t const lengthRand = FUZ_RANDLENGTH + 4;
+            size_t const lengthRand = FUZ_ABOUT(4);
             size_t const length = MIN(lengthRand, bufferSize - pos);
             size_t const end = pos + length;
-            while (pos < end) BBuffer[pos++] = (BYTE)(FUZ_rand(seed) >> 5);
+            while (pos < end) BBuffer[pos++] = FUZ_LITERAL;
     }   }
 }
 
-
 static unsigned FUZ_highbit(U32 v32)
 {
     unsigned nbBits = 0;
@@ -214,17 +215,76 @@
 /*-*******************************************************
 *  Tests
 *********************************************************/
+
+#define CONTROL(c) { \
+    if (!(c)) {      \
+        DISPLAY("Error (line %i) => %s not respected \n", __LINE__, #c); \
+        return 1;    \
+}   }
+
+static int bug1227(void)
+{
+    LZ4F_dctx* dctx;
+    CONTROL(!LZ4F_isError(LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION)));
+
+    /* first session */
+    {   const char s9Buffer[9] = { 0 };
+        char d9Buffer[sizeof(s9Buffer)];
+        size_t const c9SizeBound = LZ4F_compressFrameBound(sizeof(s9Buffer), NULL);
+        void* const c9Buffer = malloc(c9SizeBound);
+        /* First compress a valid frame */
+        LZ4F_preferences_t pref = LZ4F_INIT_PREFERENCES;
+        pref.frameInfo.contentSize = sizeof(s9Buffer);
+        CONTROL(c9Buffer != NULL);
+        {   size_t const c9Size = LZ4F_compressFrame(c9Buffer, c9SizeBound, s9Buffer, sizeof(s9Buffer), &pref);
+            CONTROL(!LZ4F_isError(c9Size));
+            assert(c9Size > 15);
+            /* decompress it, but do not complete the process - state not terminated correctly */
+            {   size_t dstSize = sizeof(d9Buffer);
+                size_t srcSize = 15;
+                size_t const d9Size = LZ4F_decompress(dctx, d9Buffer, &dstSize, c9Buffer, &srcSize, NULL);
+                CONTROL(!LZ4F_isError(d9Size));
+                CONTROL(srcSize < c9Size); /* not entirely consumed */
+            }
+        }
+        free(c9Buffer);
+    }
+    LZ4F_resetDecompressionContext(dctx); /* unfinished session -> reset should make it clean */
+
+    /* second session : generate a valid 0-size frame with no content size field (default) */
+    {   size_t const c0SizeBound = LZ4F_compressFrameBound(0, NULL);
+        void* const c0Buffer = malloc(c0SizeBound);
+        char d0Buffer[1];
+        CONTROL(c0Buffer != NULL);
+        {   size_t const c0Size = LZ4F_compressFrame(c0Buffer, c0SizeBound, NULL, 0, NULL);
+            CONTROL(!LZ4F_isError(c0Size));
+            /* now decompress this valid empty frame */
+            {   size_t dstSize = sizeof(d0Buffer);
+                size_t srcSize = c0Size;
+                size_t const d0Size = LZ4F_decompress(dctx, d0Buffer, &dstSize, c0Buffer, &srcSize, NULL);
+                CONTROL(!LZ4F_isError(d0Size));
+                CONTROL(dstSize == 0);
+                CONTROL(srcSize == c0Size);
+        }   }
+        free(c0Buffer);
+    }
+
+    LZ4F_freeDecompressionContext(dctx);
+    return 0;
+}
+
 #define CHECK_V(v,f) v = f; if (LZ4F_isError(v)) { fprintf(stderr, "%s \n", LZ4F_getErrorName(v)); goto _output_error; }
 #define CHECK(f)   { LZ4F_errorCode_t const CHECK_V(err_ , f); }
 
-int basicTests(U32 seed, double compressibility)
+static int unitTests(U32 seed, double compressibility)
 {
 #define COMPRESSIBLE_NOISE_LENGTH (2 MB)
     void* const CNBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH);
     size_t const cBuffSize = LZ4F_compressFrameBound(COMPRESSIBLE_NOISE_LENGTH, NULL);
     void* const compressedBuffer = malloc(cBuffSize);
     void* const decodedBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH);
-    U32 randState = seed;
+    U32 randVal = seed;
+    U32* const randState = &randVal;
     size_t cSize, testSize;
     LZ4F_decompressionContext_t dCtx = NULL;
     LZ4F_compressionContext_t cctx = NULL;
@@ -237,7 +297,7 @@
         DISPLAY("allocation error, not enough memory to start fuzzer tests \n");
         goto _output_error;
     }
-    FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, &randState);
+    FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, randState);
     crcOrig = XXH64(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, 1);
 
     /* LZ4F_compressBound() : special case : srcSize == 0 */
@@ -446,8 +506,8 @@
 
         DISPLAYLEVEL(3, "random segment sizes : ");
         while (ip < iend) {
-            unsigned const nbBits = FUZ_rand(&randState) % maxBits;
-            size_t iSize = (FUZ_rand(&randState) & ((1<<nbBits)-1)) + 1;
+            unsigned const nbBits = FUZ_rand(randState) % maxBits;
+            size_t iSize = RAND_BITS(nbBits) + 1;
             size_t oSize = (size_t)(oend-op);
             if (iSize > (size_t)(iend-ip)) iSize = (size_t)(iend-ip);
             CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) );
@@ -484,7 +544,7 @@
     prefs.frameInfo.blockSizeID = LZ4F_max4MB;
     prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;
     {   size_t const dstCapacity = LZ4F_compressFrameBound(testSize, &prefs);
-        DISPLAYLEVEL(4, "dstCapacity = %u  ; ", (U32)dstCapacity)
+        DISPLAYLEVEL(4, "dstCapacity = %u  ; ", (U32)dstCapacity);
         CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, dstCapacity, CNBuffer, testSize, &prefs) );
         DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize);
     }
@@ -492,7 +552,7 @@
     DISPLAYLEVEL(3, "without frame checksum : ");
     prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum;
     {   size_t const dstCapacity = LZ4F_compressFrameBound(testSize, &prefs);
-        DISPLAYLEVEL(4, "dstCapacity = %u  ; ", (U32)dstCapacity)
+        DISPLAYLEVEL(4, "dstCapacity = %u  ; ", (U32)dstCapacity);
         CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, dstCapacity, CNBuffer, testSize, &prefs) );
         DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize);
     }
@@ -584,7 +644,72 @@
         CHECK( LZ4F_freeCompressionContext(cctx) ); cctx = NULL;
     }
 
-    /* Dictionary compression test */
+    /* Raw Dictionary compression test */
+    {   size_t const dictSize = 7 KB; /* small enough for LZ4_MEMORY_USAGE == 10 */
+        size_t const srcSize = 66 KB; /* must be > 64 KB to avoid short-size optimizations */
+        size_t const dstCapacity = LZ4F_compressFrameBound(srcSize, NULL);
+        size_t cSizeNoDict, cSizeWithDict;
+        const void* dict = CNBuffer;
+        const void* src = (const char*)CNBuffer + dictSize;
+        char* cPtr = (char*)compressedBuffer;
+        CHECK( LZ4F_createCompressionContext(&cctx, LZ4F_VERSION) );
+
+        /* compress without dictionary, just to establish a comparison point */
+        CHECK_V(cSizeNoDict,
+                LZ4F_compressFrame(compressedBuffer, dstCapacity,
+                                    src, srcSize,
+                                    NULL) );
+        /* note: NULL preferences ==> 64 KB linked blocks */
+
+        /* now compress with dictionary */
+        DISPLAYLEVEL(3, "LZ4F_compressBegin_usingDict: ");
+        cSizeWithDict = 0;
+        {   size_t hSize = LZ4F_compressBegin_usingDict(cctx, cPtr, dstCapacity, dict, dictSize, NULL);
+            //size_t hSize = LZ4F_compressBegin(cctx, cPtr, dstCapacity, NULL);
+            CHECK(hSize);
+            cSizeWithDict += hSize;
+            cPtr += hSize;
+        }
+        {   size_t bSize = LZ4F_compressUpdate(cctx, cPtr, dstCapacity, src, srcSize, NULL);
+            CHECK(bSize);
+            cSizeWithDict += bSize;
+            cPtr += bSize;
+        }
+        {   size_t endSize = LZ4F_compressEnd(cctx, cPtr, dstCapacity, NULL);
+            CHECK(endSize);
+            cSizeWithDict += endSize;
+        }
+        DISPLAYLEVEL(3, "compress %u bytes into %u bytes with dict (< %u bytes without) \n",
+                        (unsigned)srcSize, (unsigned)cSizeWithDict, (unsigned)cSizeNoDict);
+        if (cSizeWithDict >= cSizeNoDict) {
+            DISPLAYLEVEL(3, "cSizeWithDict (%u) should have been more compact than cSizeNoDict(%u) \n", (unsigned)cSizeWithDict, (unsigned)cSizeNoDict);
+            goto _output_error;  /* must be more efficient */
+        }
+        crcOrig = XXH64(src, srcSize, 0);
+
+        DISPLAYLEVEL(3, "LZ4F_decompress_usingDict: ");
+        {   LZ4F_dctx* dctx;
+            size_t decodedSize = srcSize;
+            size_t compressedSize = cSizeWithDict;
+            CHECK( LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION) );
+            CHECK( LZ4F_decompress_usingDict(dctx,
+                                        decodedBuffer, &decodedSize,
+                                        compressedBuffer, &compressedSize,
+                                        CNBuffer, dictSize,
+                                        NULL) );
+            if (compressedSize != cSizeWithDict) goto _output_error;
+            if (decodedSize != srcSize) goto _output_error;
+            { U64 const crcDest = XXH64(decodedBuffer, decodedSize, 0);
+              if (crcDest != crcOrig) goto _output_error; }
+            DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize);
+            CHECK( LZ4F_freeDecompressionContext(dctx) );
+        }
+
+        /* clean */
+        CHECK( LZ4F_freeCompressionContext(cctx) );
+    }
+
+    /* Digested Dictionary (cdict) compression test */
     {   size_t const dictSize = 7 KB; /* small enough for LZ4_MEMORY_USAGE == 10 */
         size_t const srcSize = 65 KB; /* must be > 64 KB to avoid short-size optimizations */
         size_t const dstCapacity = LZ4F_compressFrameBound(srcSize, NULL);
@@ -607,9 +732,9 @@
                                               NULL, NULL) );
         DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cSizeNoDict);
 
+        DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with dict : ");
         CHECK( LZ4F_freeCompressionContext(cctx) );
         CHECK( LZ4F_createCompressionContext(&cctx, LZ4F_VERSION) );
-        DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with dict : ");
         CHECK_V(cSizeWithDict,
                 LZ4F_compressFrame_usingCDict(cctx, compressedBuffer, dstCapacity,
                                               CNBuffer, srcSize,
@@ -617,7 +742,7 @@
         DISPLAYLEVEL(3, "compressed %u bytes into %u bytes \n",
                         (unsigned)srcSize, (unsigned)cSizeWithDict);
         if (cSizeWithDict > cSizeNoDict) {
-            DISPLAYLEVEL(3, "cSizeWithDict (%zu) should have been more compact than cSizeNoDict(%zu) \n", cSizeWithDict, cSizeNoDict);
+            DISPLAYLEVEL(3, "cSizeWithDict (%u) should have been more compact than cSizeNoDict(%u) \n", (unsigned)cSizeWithDict, (unsigned)cSizeNoDict);
             goto _output_error;  /* must be more efficient */
         }
         crcOrig = XXH64(CNBuffer, srcSize, 0);
@@ -699,7 +824,6 @@
             }
         }
 
-
         DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, multiple independent blocks : ");
         {   size_t cSizeIndep;
             size_t const inSize = dictSize * 3;
@@ -762,6 +886,9 @@
         goto _output_error;
     }
 
+    DISPLAYLEVEL(3, "check bug1227: reused dctx after error => ");
+    if (bug1227()) goto _output_error;
+    DISPLAYLEVEL(3, "OK \n");
 
     DISPLAYLEVEL(3, "Skippable frame test : \n");
     {   size_t decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH;
@@ -779,8 +906,8 @@
 
         DISPLAYLEVEL(3, "random segment sizes : \n");
         while (ip < iend) {
-            unsigned nbBits = FUZ_rand(&randState) % maxBits;
-            size_t iSize = (FUZ_rand(&randState) & ((1<<nbBits)-1)) + 1;
+            unsigned nbBits = FUZ_rand(randState) % maxBits;
+            size_t iSize = RAND_BITS(nbBits) + 1;
             size_t oSize = (size_t)(oend-op);
             if (iSize > (size_t)(iend-ip)) iSize = (size_t)(iend-ip);
             CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) );
@@ -798,8 +925,8 @@
         iend = ip+8;
 
         while (ip < iend) {
-            unsigned const nbBits = FUZ_rand(&randState) % maxBits;
-            size_t iSize = (FUZ_rand(&randState) & ((1<<nbBits)-1)) + 1;
+            unsigned const nbBits = FUZ_rand(randState) % maxBits;
+            size_t iSize = RAND_BITS(nbBits) + 1;
             size_t oSize = (size_t)(oend-op);
             if (iSize > (size_t)(iend-ip)) iSize = (size_t)(iend-ip);
             CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) );
@@ -862,11 +989,10 @@
     }
 }
 
-#   define EXIT_MSG(...) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \
-                           DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb); exit(1); }
-#   undef CHECK
-#   define CHECK(cond, ...) { if (cond) { EXIT_MSG(__VA_ARGS__); } }
-
+#define EXIT_MSG(...) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \
+                        DISPLAY(" (seed %u, test nb %u)  \n", seed, testNb); exit(1); }
+#undef CHECK
+#define CHECK(cond, ...) { if (cond) { EXIT_MSG(__VA_ARGS__); } }
 
 size_t test_lz4f_decompression_wBuffers(
           const void* cSrc, size_t cSize,
@@ -894,27 +1020,28 @@
     while (ip < iend) {
         unsigned const nbBitsI = (FUZ_rand(randState) % (maxBits-1)) + 1;
         unsigned const nbBitsO = (FUZ_rand(randState) % (maxBits)) + 1;
-        size_t const iSizeCand = (FUZ_rand(randState) & ((1<<nbBitsI)-1)) + 1;
+        size_t const iSizeCand = RAND_BITS(nbBitsI) + 1;
         size_t const iSizeMax = MIN(iSizeCand, (size_t)(iend-ip));
         size_t iSize = iSizeMax;
-        size_t const oSizeCand = (FUZ_rand(randState) & ((1<<nbBitsO)-1)) + 2;
+        size_t const oSizeCand = RAND_BITS(nbBitsO) + 2;
         size_t const oSizeMax = MIN(oSizeCand, (size_t)(oend-op));
         int const sentinelTest = (op + oSizeMax < oend);
         size_t oSize = oSizeMax;
-        BYTE const mark = (BYTE)(FUZ_rand(randState) & 255);
+        BYTE const mark = (BYTE)(RAND_BITS(8));
         LZ4F_decompressOptions_t dOptions;
         memset(&dOptions, 0, sizeof(dOptions));
-        dOptions.stableDst = FUZ_rand(randState) & 1;
+        dOptions.stableDst = RAND_BITS(1);
         if (o_scenario == o_overwrite) dOptions.stableDst = 0;  /* overwrite mode */
-        dOptions.skipChecksums = FUZ_rand(randState) & 127;
+        dOptions.skipChecksums = RAND_BITS(1);
         if (sentinelTest) op[oSizeMax] = mark;
 
         DISPLAYLEVEL(7, "dstCapacity=%u,  presentedInput=%u \n", (unsigned)oSize, (unsigned)iSize);
 
         /* read data from byte-exact buffer to catch out-of-bound reads */
         {   void* const iBuffer = malloc(iSizeMax);
-            void* const tmpop = (FUZ_rand(randState) & (oSize == 0)) ? NULL : op;
-            const void* const tmpip = (FUZ_rand(randState) & (iSize == 0)) ? NULL : iBuffer;
+            /*test NULL supported if size==0 */
+            void* const tmpop = RAND_BITS(oSize == 0) ? NULL : op;
+            const void* const tmpip = RAND_BITS(iSize == 0) ? NULL : iBuffer;
             assert(iBuffer != NULL);
             memcpy(iBuffer, ip, iSizeMax);
             moreToFlush = LZ4F_decompress(dCtx, tmpop, &oSize, tmpip, &iSize, &dOptions);
@@ -997,7 +1124,6 @@
     void* decodedBuffer = NULL;
     U32 coreRand = seed;
     LZ4F_decompressionContext_t dCtx = NULL;
-    LZ4F_decompressionContext_t dCtxNoise = NULL;
     LZ4F_compressionContext_t cCtx = NULL;
     clock_t const startClock = clock();
     clock_t const clockDuration = duration_s * CLOCKS_PER_SEC;
@@ -1005,8 +1131,6 @@
     /* Create states & buffers */
     {   size_t const creationStatus = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
         CHECK(LZ4F_isError(creationStatus), "Allocation failed (error %i)", (int)creationStatus); }
-    {   size_t const creationStatus = LZ4F_createDecompressionContext(&dCtxNoise, LZ4F_VERSION);
-        CHECK(LZ4F_isError(creationStatus), "Allocation failed (error %i)", (int)creationStatus); }
     {   size_t const creationStatus = LZ4F_createCompressionContext(&cCtx, LZ4F_VERSION);
         CHECK(LZ4F_isError(creationStatus), "Allocation failed (error %i)", (int)creationStatus); }
     CNBuffer = malloc(CNBufferLength);
@@ -1024,7 +1148,7 @@
     for ( ; (testNb < nbTests) || (clockDuration > FUZ_GetClockSpan(startClock)) ; testNb++) {
         U32 randState = coreRand ^ prime1;
         unsigned const srcBits = (FUZ_rand(&randState) % (FUZ_highbit((U32)(CNBufferLength-1)) - 1)) + 1;
-        size_t const srcSize = (FUZ_rand(&randState) & ((1<<srcBits)-1)) + 1;
+        size_t const srcSize = (FUZ_rand(&randState) & ((1<<srcBits)-1));
         size_t const srcStartId = FUZ_rand(&randState) % (CNBufferLength - srcSize);
         const BYTE* const srcStart = (const BYTE*)CNBuffer + srcStartId;
         unsigned const neverFlush = (FUZ_rand(&randState) & 15) == 1;
@@ -1153,8 +1277,7 @@
                                         (int)result, LZ4F_getErrorName(result));
         }
 
-#if 1
-        /* insert noise into src */
+        /* insert noise into src - ensure decoder survives with no sanitizer error */
         {   U32 const maxNbBits = FUZ_highbit((U32)cSize);
             size_t pos = 0;
             for (;;) {
@@ -1178,18 +1301,16 @@
 
         /* test decompression on noisy src */
         DISPLAYLEVEL(6, "noisy decompression \n");
-        test_lz4f_decompression(compressedBuffer, cSize, srcStart, srcSize, crcOrig, &randState, dCtxNoise, seed, testNb, 0 /*don't search error Pos*/ );
+        test_lz4f_decompression(compressedBuffer, cSize, srcStart, srcSize, crcOrig, &randState, dCtx, seed, testNb, 0 /*don't search error Pos*/ );
         /* note : we don't analyze result here : it probably failed, which is expected.
          * The sole purpose is to catch potential out-of-bound reads and writes. */
-        LZ4F_resetDecompressionContext(dCtxNoise);  /* context must be reset after an error */
-#endif
+        LZ4F_resetDecompressionContext(dCtx);  /* state must be reset to clean after an error */
 
-}   /* for ( ; (testNb < nbTests) ; ) */
+    }   /* for ( ; (testNb < nbTests) ; ) */
 
     DISPLAYLEVEL(2, "\rAll tests completed   \n");
 
     LZ4F_freeDecompressionContext(dCtx);
-    LZ4F_freeDecompressionContext(dCtxNoise);
     LZ4F_freeCompressionContext(cCtx);
     free(CNBuffer);
     free(compressedBuffer);
@@ -1228,7 +1349,6 @@
     unsigned nbTests = nbTestsDefault;
     unsigned testNb = 0;
     int proba = FUZ_COMPRESSIBILITY_DEFAULT;
-    int result=0;
     U32 duration=0;
     const char* const programName = argv[0];
 
@@ -1335,23 +1455,29 @@
                     return FUZ_usage(programName);
                 }
             }
-        }
-    }
+        } /* if (argument[0]=='-') */
+    } /* for (argNb=1; argNb<argc; argNb++) */
 
-    /* Get Seed */
-    DISPLAY("Starting lz4frame tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), LZ4_VERSION_STRING);
+    DISPLAY("Starting lz4frame tester (%i-bits, %s) \n", (int)(sizeof(size_t)*8), LZ4_VERSION_STRING);
 
+    /* Select a random seed if none given */
     if (!seedset) {
         time_t const t = time(NULL);
         U32 const h = XXH32(&t, sizeof(t), 1);
         seed = h % 10000;
     }
-    DISPLAY("Seed = %u\n", seed);
-    if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba);
+    DISPLAY("Seed = %u \n", seed);
+    if (proba != FUZ_COMPRESSIBILITY_DEFAULT)
+        DISPLAY("Compressibility : %i%% \n", proba);
 
-    nbTests += (nbTests==0);  /* avoid zero */
+    {   double const compressibility = (double)proba / 100;
+        /* start by unit tests if not requesting a specific run nb */
+        if (testNb==0) {
+            if (unitTests(seed, compressibility))
+                return 1;
+        }
 
-    if (testNb==0) result = basicTests(seed, ((double)proba) / 100);
-    if (result) return 1;
-    return fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100, duration);
+        nbTests += (nbTests==0);  /* avoid zero */
+        return fuzzerTests(seed, nbTests, testNb, compressibility, duration);
+    }
 }
diff --git a/tests/freestanding.c b/tests/freestanding.c
index ceff4c5..6109aa7 100644
--- a/tests/freestanding.c
+++ b/tests/freestanding.c
@@ -30,7 +30,6 @@
 
 
 #if !defined(__x86_64__) || !defined(__linux__)
-EXTERN_C void _start(void) { }
 int main(int argc, char** argv) { return 0; }
 #else
 
diff --git a/tests/fullbench.c b/tests/fullbench.c
index 9c13996..ac73ed2 100644
--- a/tests/fullbench.c
+++ b/tests/fullbench.c
@@ -58,7 +58,7 @@
 #define WELCOME_MESSAGE "*** %s v%s %i-bits, by %s ***\n", PROGRAM_DESCRIPTION, LZ4_VERSION_STRING, (int)(sizeof(void*)*8), AUTHOR
 
 #define NBLOOPS    6
-#define TIMELOOP   (CLOCKS_PER_SEC * 25 / 10)
+#define TIMELOOP   (CLOCKS_PER_SEC * 19 / 10)
 
 #define KB *(1 <<10)
 #define MB *(1 <<20)
@@ -179,6 +179,13 @@
     assert(r != NULL); (void)r;
 }
 
+static void* g_chunk0 = NULL;
+static size_t g_chunk0Size = 0;
+static void local_LZ4_saveDict_init(void)
+{
+    LZ4_loadDict(&LZ4_stream, (const char*)g_chunk0, (int)g_chunk0Size);
+}
+
 static int local_LZ4_saveDict(const char* in, char* out, int inSize)
 {
     (void)in;
@@ -256,6 +263,11 @@
     LZ4_initStreamHC(&LZ4_streamHC, sizeof(LZ4_streamHC));
 }
 
+static void local_LZ4_saveDictHC_init(void)
+{
+    LZ4_loadDictHC(&LZ4_streamHC, (const char*)g_chunk0, (int)g_chunk0Size);
+}
+
 static int local_LZ4_saveDictHC(const char* in, char* out, int inSize)
 {
     (void)in;
@@ -300,6 +312,11 @@
     return outSize;
 }
 
+static int local_LZ4_decompress_safe(const char* in, char* out, int inSize, int outSize)
+{
+    return LZ4_decompress_safe(in, out, inSize, outSize);
+}
+
 static int local_LZ4_decompress_safe_withPrefix64k(const char* in, char* out, int inSize, int outSize)
 {
     LZ4_decompress_safe_withPrefix64k(in, out, inSize, outSize);
@@ -371,6 +388,33 @@
     return (int)LZ4F_compressFrame(out, LZ4F_compressFrameBound((size_t)inSize, NULL), in, (size_t)inSize, NULL);
 }
 
+LZ4F_cctx* g_cctx = NULL;
+static int local_LZ4F_compress(const char* in, char* out, int inSize)
+{
+    /* output buffer size is assumed */
+    size_t const outSize = LZ4F_compressFrameBound((size_t)inSize, NULL);
+    size_t cSize = 0;
+    assert(inSize >= 0);
+    if (g_cctx == NULL) {
+        /* create and initialize LZ4F compression context the first time */
+        LZ4F_createCompressionContext(&g_cctx, LZ4F_VERSION);
+        assert(g_cctx != NULL);
+    } /* re-use existing compression context otherwise */
+    {   size_t const cbSize = LZ4F_compressBegin(g_cctx, out, outSize, NULL);
+        assert(!LZ4F_isError(cbSize));
+        cSize += cbSize;
+    }
+    {   size_t const cuSize = LZ4F_compressUpdate(g_cctx, out+cSize, outSize-cSize, in, (size_t)inSize, NULL);
+        assert(!LZ4F_isError(cuSize));
+        cSize += cuSize;
+    }
+    {   size_t const ceSize = LZ4F_compressEnd(g_cctx, out+cSize, outSize-cSize, NULL);
+        assert(!LZ4F_isError(ceSize));
+        cSize += ceSize;
+    }
+    return (int)cSize;
+}
+
 static LZ4F_decompressionContext_t g_dCtx;
 
 static int local_LZ4F_decompress(const char* in, char* out, int inSize, int outSize)
@@ -454,11 +498,77 @@
 
 }
 
-#define NB_COMPRESSION_ALGORITHMS 100
-#define NB_DECOMPRESSION_ALGORITHMS 100
+typedef struct {
+    const char* name;
+    int (*compressionF)(const char*, char*, int);
+    void (*initFunction)(void);
+    int singleChunk;
+} CompressionDesc;
+
+static const CompressionDesc compDescArray[] = {
+    { NULL, NULL, NULL, 0 },
+    { "LZ4_compress_default", local_LZ4_compress_default_large, NULL, 0 },
+    { "LZ4_compress_default(small dst)", local_LZ4_compress_default_small, NULL, 0 },
+    { "LZ4_compress_destSize", local_LZ4_compress_destSize, NULL, 0 },
+    { "LZ4_compress_fast(0)", local_LZ4_compress_fast0, NULL, 0 },
+    { "LZ4_compress_fast(1)", local_LZ4_compress_fast1, NULL, 0 },
+    { "LZ4_compress_fast(2)", local_LZ4_compress_fast2, NULL, 0 },
+    { "LZ4_compress_fast(17)", local_LZ4_compress_fast17, NULL, 0 },
+    { "LZ4_compress_fast_extState(0)", local_LZ4_compress_fast_extState0, NULL, 0 },
+    { "LZ4_compress_fast_continue(0)", local_LZ4_compress_fast_continue0, local_LZ4_createStream, 0 },
+    { "LZ4_compress_HC", local_LZ4_compress_HC, NULL, 0 },
+    { "LZ4_compress_HC_extStateHC", local_LZ4_compress_HC_extStateHC, NULL, 0 },
+    { "LZ4_compress_HC_continue", local_LZ4_compress_HC_continue, local_LZ4_resetStreamHC, 0 },
+#ifndef LZ4_DLL_IMPORT
+    { "LZ4_compress_forceDict", local_LZ4_compress_forceDict, local_LZ4_resetDictT, 0 },
+#endif
+    { "LZ4F_compressFrame", local_LZ4F_compressFrame, NULL, 1 },
+    { "LZ4F_compressUpdate", local_LZ4F_compress, NULL, 1 },
+    { "LZ4_saveDict", local_LZ4_saveDict, local_LZ4_saveDict_init, 0 },
+    { "LZ4_saveDictHC", local_LZ4_saveDictHC, local_LZ4_saveDictHC_init, 0 },
+
+};
+
+typedef struct {
+    const char* name;
+    int (*decompressionF)(const char*, char*, int, int);
+    int checkResult;
+    int frameFormat;
+} DecompressionDesc;
+
+static const DecompressionDesc decDescArray[] = {
+    { NULL, NULL, 0, 0 },
+    { "LZ4_decompress_fast", local_LZ4_decompress_fast, 1, 0 },
+    { "LZ4_decompress_fast_usingDict(prefix)", local_LZ4_decompress_fast_usingDict_prefix, 1, 0 },
+    { "LZ4_decompress_fast_using(Ext)Dict", local_LZ4_decompress_fast_usingExtDict, 1, 0 },
+    { "LZ4_decompress_safe", local_LZ4_decompress_safe, 1, 0 },
+    { "LZ4_decompress_safe_withPrefix64k", local_LZ4_decompress_safe_withPrefix64k, 1, 0 },
+    { "LZ4_decompress_safe_usingDict", local_LZ4_decompress_safe_usingDict, 1, 0 },
+    { "LZ4_decompress_safe_partial", local_LZ4_decompress_safe_partial, 0, 0 },
+    { "LZ4_decompress_safe_partial_usingDict", local_LZ4_decompress_safe_partial_usingDict, 0, 0 },
+#ifndef LZ4_DLL_IMPORT
+    { "LZ4_decompress_safe_partial_forceExtDict", local_LZ4_decompress_safe_partial_forceExtDict, 0, 0 },
+    { "LZ4_decompress_safe_forceExtDict", local_LZ4_decompress_safe_forceExtDict, 1, 0 },
+#endif
+    { "LZ4F_decompress", local_LZ4F_decompress, 1, 1 },
+    { "LZ4F_decompLZ4F_decompress_followHintress", local_LZ4F_decompress_followHint, 1, 1 },
+    { "LZ4F_decompress_noHint", local_LZ4F_decompress_noHint, 1, 1 },
+};
+
+#define ARRAY_SIZE(a) (sizeof(a) / (sizeof((a)[0])))
+
+#define NB_COMPRESSION_ALGORITHMS ARRAY_SIZE(compDescArray)
+#define NB_DECOMPRESSION_ALGORITHMS ARRAY_SIZE(decDescArray)
+
 int fullSpeedBench(const char** fileNamesTable, int nbFiles)
 {
     int fileIdx=0;
+    clock_t loopDuration = TIMELOOP;
+
+    if (g_nbIterations==0) {
+        loopDuration = CLOCKS_PER_SEC / 50 + 1;
+        g_nbIterations = 1;
+    }
 
     /* Init */
     { size_t const errorCode = LZ4F_createDecompressionContext(&g_dCtx, LZ4F_VERSION);
@@ -490,11 +600,15 @@
           DISPLAY("Not enough memory for '%s' full size; testing %i MB only... \n",
                 inFileName, (int)(benchedSize>>20));
       }
+      if (benchedSize < 8 || g_chunkSize < 8) {
+        DISPLAY(" cannot bench using less then 8 bytes \n");
+        return 1;
+      }
 
       /* Allocation */
-      chunkP = (struct chunkParameters*) malloc(((benchedSize / (size_t)g_chunkSize)+1) * sizeof(struct chunkParameters));
-      orig_buff = (char*) malloc(benchedSize);
       nbChunks = (int) ((benchedSize + (size_t)g_chunkSize - 1) / (size_t)g_chunkSize);
+      chunkP = (struct chunkParameters*) malloc((size_t)nbChunks * sizeof(chunkP[0]));
+      orig_buff = (char*) malloc(benchedSize);
       maxCompressedChunkSize = LZ4_compressBound(g_chunkSize);
       compressedBuffSize = nbChunks * maxCompressedChunkSize;
       compressed_buff = (char*)malloc((size_t)compressedBuffSize);
@@ -523,7 +637,6 @@
       /* Calculating input Checksum */
       crcOriginal = XXH32(orig_buff, benchedSize,0);
 
-
       /* Bench */
       { int loopNb, nb_loops, chunkNb, cAlgNb, dAlgNb;
         size_t cSize=0;
@@ -533,7 +646,7 @@
         DISPLAY(" %s : \n", inFileName);
 
         /* Bench Compression Algorithms */
-        for (cAlgNb=0; (cAlgNb <= NB_COMPRESSION_ALGORITHMS) && (g_compressionTest); cAlgNb++) {
+        for (cAlgNb=0; (cAlgNb <= (int)NB_COMPRESSION_ALGORITHMS) && (g_compressionTest); cAlgNb++) {
             const char* compressorName;
             int (*compressionFunction)(const char*, char*, int);
             void (*initFunction)(void) = NULL;
@@ -563,39 +676,25 @@
                     chunkP[i].compressedSize = 0;
                 }
             }
+            g_chunk0 = chunkP[0].origBuffer;
+            g_chunk0Size = (size_t)chunkP[0].origSize;
 
-            switch(cAlgNb)
-            {
-            case 0 : DISPLAY("Compression functions : \n"); continue;
-            case 1 : compressionFunction = local_LZ4_compress_default_large; compressorName = "LZ4_compress_default"; break;
-            case 2 : compressionFunction = local_LZ4_compress_default_small; compressorName = "LZ4_compress_default(small dst)"; break;
-            case 3 : compressionFunction = local_LZ4_compress_destSize; compressorName = "LZ4_compress_destSize"; break;
-            case 4 : compressionFunction = local_LZ4_compress_fast0; compressorName = "LZ4_compress_fast(0)"; break;
-            case 5 : compressionFunction = local_LZ4_compress_fast1; compressorName = "LZ4_compress_fast(1)"; break;
-            case 6 : compressionFunction = local_LZ4_compress_fast2; compressorName = "LZ4_compress_fast(2)"; break;
-            case 7 : compressionFunction = local_LZ4_compress_fast17; compressorName = "LZ4_compress_fast(17)"; break;
-            case 8 : compressionFunction = local_LZ4_compress_fast_extState0; compressorName = "LZ4_compress_fast_extState(0)"; break;
-            case 9 : compressionFunction = local_LZ4_compress_fast_continue0; initFunction = local_LZ4_createStream; compressorName = "LZ4_compress_fast_continue(0)"; break;
-
-            case 10: compressionFunction = local_LZ4_compress_HC; compressorName = "LZ4_compress_HC"; break;
-            case 12: compressionFunction = local_LZ4_compress_HC_extStateHC; compressorName = "LZ4_compress_HC_extStateHC"; break;
-            case 14: compressionFunction = local_LZ4_compress_HC_continue; initFunction = local_LZ4_resetStreamHC; compressorName = "LZ4_compress_HC_continue"; break;
-#ifndef LZ4_DLL_IMPORT
-            case 20: compressionFunction = local_LZ4_compress_forceDict; initFunction = local_LZ4_resetDictT; compressorName = "LZ4_compress_forceDict"; break;
-#endif
-            case 30: compressionFunction = local_LZ4F_compressFrame; compressorName = "LZ4F_compressFrame";
-                        chunkP[0].origSize = (int)benchedSize; nbChunks=1;
-                        break;
-            case 40: compressionFunction = local_LZ4_saveDict; compressorName = "LZ4_saveDict";
-                        if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; }
-                        LZ4_loadDict(&LZ4_stream, chunkP[0].origBuffer, chunkP[0].origSize);
-                        break;
-            case 41: compressionFunction = local_LZ4_saveDictHC; compressorName = "LZ4_saveDictHC";
-                        if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; }
-                        LZ4_loadDictHC(&LZ4_streamHC, chunkP[0].origBuffer, chunkP[0].origSize);
-                        break;
-            default :
-                continue;   /* unknown ID : just skip */
+            if (cAlgNb==0) {
+                DISPLAY("Compression functions : \n");
+                continue;
+            }
+            if (cAlgNb >= (int)NB_COMPRESSION_ALGORITHMS) {
+                continue;
+            }
+            compressorName = compDescArray[cAlgNb].name;
+            compressionFunction = compDescArray[cAlgNb].compressionF;
+            initFunction = compDescArray[cAlgNb].initFunction;
+            if (compDescArray[cAlgNb].singleChunk) {
+                nbChunks=1;
+                chunkP[0].origSize = (int)benchedSize;
+            }
+            if (compressorName==NULL || compressionFunction==NULL) {
+                continue;
             }
 
             for (loopNb = 1; loopNb <= g_nbIterations; loopNb++) {
@@ -609,7 +708,7 @@
                 clockTime = clock();
                 while(clock() == clockTime);
                 clockTime = clock();
-                while(BMK_GetClockSpan(clockTime) < TIMELOOP) {
+                while(BMK_GetClockSpan(clockTime) < loopDuration) {
                     if (initFunction!=NULL) initFunction();
                     for (chunkNb=0; chunkNb<nbChunks; chunkNb++) {
                         chunkP[chunkNb].compressedSize = compressionFunction(chunkP[chunkNb].origBuffer, chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origSize);
@@ -665,7 +764,7 @@
         }   }
 
         /* Decompression Algorithms */
-        for (dAlgNb=0; (dAlgNb <= NB_DECOMPRESSION_ALGORITHMS) && g_decompressionTest; dAlgNb++) {
+        for (dAlgNb=0; (dAlgNb <= (int)NB_DECOMPRESSION_ALGORITHMS) && g_decompressionTest; dAlgNb++) {
             const char* dName = NULL;
             int (*decompressionFunction)(const char*, char*, int, int) = NULL;
             double bestTime = 100000000.;
@@ -673,41 +772,25 @@
 
             if ((g_decompressionAlgo != ALL_DECOMPRESSORS) && (g_decompressionAlgo != dAlgNb)) continue;
 
-            switch(dAlgNb)
-            {
-            case 0: DISPLAY("Decompression functions : \n"); continue;
-            case 1: decompressionFunction = local_LZ4_decompress_fast; dName = "LZ4_decompress_fast"; break;
-            case 2: decompressionFunction = local_LZ4_decompress_fast_usingDict_prefix; dName = "LZ4_decompress_fast_usingDict(prefix)"; break;
-            case 3: decompressionFunction = local_LZ4_decompress_fast_usingExtDict; dName = "LZ4_decompress_fast_using(Ext)Dict"; break;
-            case 4: decompressionFunction = LZ4_decompress_safe; dName = "LZ4_decompress_safe"; break;
-            case 5: decompressionFunction = local_LZ4_decompress_safe_withPrefix64k; dName = "LZ4_decompress_safe_withPrefix64k"; break;
-            case 6: decompressionFunction = local_LZ4_decompress_safe_usingDict; dName = "LZ4_decompress_safe_usingDict"; break;
-            case 7: decompressionFunction = local_LZ4_decompress_safe_partial; dName = "LZ4_decompress_safe_partial"; checkResult = 0; break;
-            case 8: decompressionFunction = local_LZ4_decompress_safe_partial_usingDict; dName = "LZ4_decompress_safe_partial_usingDict"; checkResult = 0; break;
-#ifndef LZ4_DLL_IMPORT
-            case 9: decompressionFunction = local_LZ4_decompress_safe_partial_forceExtDict; dName = "LZ4_decompress_safe_partial_forceExtDict"; checkResult = 0; break;
-            case 10: decompressionFunction = local_LZ4_decompress_safe_forceExtDict; dName = "LZ4_decompress_safe_forceExtDict"; break;
-#endif
-            case 11:
-            case 12:
-            case 13:
-                if (dAlgNb == 11) { decompressionFunction = local_LZ4F_decompress; dName = "LZ4F_decompress"; }  /* can be skipped */
-                if (dAlgNb == 12) { decompressionFunction = local_LZ4F_decompress_followHint; dName = "LZ4F_decompress_followHint"; }  /* can be skipped */
-                if (dAlgNb == 13) { decompressionFunction = local_LZ4F_decompress_noHint; dName = "LZ4F_decompress_noHint"; }  /* can be skipped */
-                /* prepare compressed data using frame format */
-                {   size_t const fcsize = LZ4F_compressFrame(compressed_buff, (size_t)compressedBuffSize, orig_buff, benchedSize, NULL);
-                    assert(!LZ4F_isError(fcsize));
-                    chunkP[0].origSize = (int)benchedSize;
-                    chunkP[0].compressedSize = (int)fcsize;
-                    nbChunks = 1;
-                    break;
-                }
-            default :
-                continue;   /* skip if unknown ID */
+            if (dAlgNb==0) { /* just for display */
+                DISPLAY("Decompression functions : \n");
+                continue;
             }
-
-            assert(decompressionFunction != NULL);
-            assert(dName != NULL);
+            if (dAlgNb >= (int)NB_DECOMPRESSION_ALGORITHMS)
+                continue;
+            dName = decDescArray[dAlgNb].name;
+            decompressionFunction = decDescArray[dAlgNb].decompressionF;
+            if (dName==NULL || decompressionFunction == NULL)
+                continue;
+            checkResult = decDescArray[dAlgNb].checkResult;
+            if (decDescArray[dAlgNb].frameFormat) {
+                /* prepare compressed data using LZ4F frame format */
+                size_t const fcsize = LZ4F_compressFrame(compressed_buff, (size_t)compressedBuffSize, orig_buff, benchedSize, NULL);
+                assert(!LZ4F_isError(fcsize));
+                chunkP[0].origSize = (int)benchedSize;
+                chunkP[0].compressedSize = (int)fcsize;
+                nbChunks = 1;
+            }
 
             { size_t i; for (i=0; i<benchedSize; i++) orig_buff[i]=0; }     /* zeroing source area, for CRC checking */
 
@@ -722,7 +805,7 @@
                 clockTime = clock();
                 while(clock() == clockTime);
                 clockTime = clock();
-                while(BMK_GetClockSpan(clockTime) < TIMELOOP) {
+                while(BMK_GetClockSpan(clockTime) < loopDuration) {
                     for (chunkNb=0; chunkNb<nbChunks; chunkNb++) {
                         int const decodedSize = decompressionFunction(chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origBuffer,
                                                                       chunkP[chunkNb].compressedSize, chunkP[chunkNb].origSize);
@@ -763,6 +846,23 @@
     return 0;
 }
 
+static int list(void)
+{
+    size_t n;
+    DISPLAY("Compression Algorithm ids: \n");
+    for (n=0; n<NB_COMPRESSION_ALGORITHMS; n++) {
+        if (compDescArray[n].name) {
+            DISPLAY("%2u: %s \n", (unsigned)n, compDescArray[n].name);
+        }
+    }
+    DISPLAY("Decompression Algorithm ids: \n");
+    for (n=0; n<NB_DECOMPRESSION_ALGORITHMS; n++) {
+        if (decDescArray[n].name) {
+            DISPLAY("%2u: %s \n", (unsigned)n, decDescArray[n].name);
+        }
+    }
+    return 0;
+}
 
 static int usage(const char* exename)
 {
@@ -778,11 +878,11 @@
 static int usage_advanced(void)
 {
     DISPLAY( "\nAdvanced options :\n");
-    DISPLAY( " -c#    : test only compression function # [1-%i]\n", NB_COMPRESSION_ALGORITHMS);
-    DISPLAY( " -d#    : test only decompression function # [1-%i]\n", NB_DECOMPRESSION_ALGORITHMS);
+    DISPLAY( " -c#    : test only compression function # [1-%i]\n", (int)NB_COMPRESSION_ALGORITHMS);
+    DISPLAY( " -d#    : test only decompression function # [1-%i]\n", (int)NB_DECOMPRESSION_ALGORITHMS);
     DISPLAY( " -i#    : iteration loops [1-9](default : %i)\n", NBLOOPS);
     DISPLAY( " -B#    : Block size [4-7](default : 7)\n");
-    return 0;
+    return list();
 }
 
 static int badusage(const char* exename)
@@ -842,7 +942,8 @@
 
                     // Display help on usage
                 case 'h' :
-                case 'H': usage(exename); usage_advanced(); return 0;
+                case 'H': usage(exename); return usage_advanced();
+                case 'l': return list();
 
                     // Modify Block Properties
                 case 'B':
diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index 341a2b0..c1e3bc0 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -93,7 +93,7 @@
 *  Macros
 *****************************************/
 #define DISPLAY(...)         fprintf(stdout, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYLEVEL(l, ...) do { if (g_displayLevel>=l) DISPLAY(__VA_ARGS__); } while (0)
 static int g_displayLevel = 2;
 
 #define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
@@ -329,29 +329,30 @@
     void* const stateLZ4   = malloc((size_t)LZ4_sizeofState());
     void* const stateLZ4HC = malloc((size_t)LZ4_sizeofStateHC());
     LZ4_stream_t LZ4dictBody;
-    LZ4_streamHC_t* LZ4dictHC = LZ4_createStreamHC();
+    LZ4_streamHC_t* const LZ4dictHC = LZ4_createStreamHC();
     U32 coreRandState = seed;
     clock_t const clockStart = clock();
     clock_t const clockDuration = (clock_t)duration_s * CLOCKS_PER_SEC;
     int result = 0;
     unsigned cycleNb;
 
-#   define EXIT_MSG(...) {                             \
+#   define EXIT_MSG(...) do {                          \
     printf("Test %u : ", testNb); printf(__VA_ARGS__); \
     printf(" (seed %u, cycle %u) \n", seed, cycleNb);  \
     exit(1);                                           \
-}
+} while (0)
 
-#   define FUZ_CHECKTEST(cond, ...)  if (cond) { EXIT_MSG(__VA_ARGS__) }
+#   define FUZ_CHECKTEST(cond, ...)  do { if (cond) EXIT_MSG(__VA_ARGS__); } while (0)
 
-#   define FUZ_DISPLAYTEST(...) {                 \
+#   define FUZ_DISPLAYTEST(...) do {              \
                 testNb++;                         \
                 if (g_displayLevel>=4) {          \
                     printf("\r%4u - %2u :", cycleNb, testNb);  \
                     printf(" " __VA_ARGS__);      \
                     printf("   ");                \
                     fflush(stdout);               \
-            }   }
+                }                                 \
+            } while (0)
 
 
     /* init */
@@ -465,7 +466,7 @@
         /* Test compression HC using external state */
         FUZ_DISPLAYTEST("test LZ4_compress_HC_extStateHC()");
         {   int const r = LZ4_compress_HC_extStateHC(stateLZ4HC, block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel);
-            FUZ_CHECKTEST(r==0, "LZ4_compress_HC_extStateHC() failed")
+            FUZ_CHECKTEST(r==0, "LZ4_compress_HC_extStateHC() failed");
         }
 
         /* Test compression HC using fast reset external state */
@@ -477,10 +478,23 @@
         /* Test compression using external state */
         FUZ_DISPLAYTEST("test LZ4_compress_fast_extState()");
         {   int const r = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, (int)compressedBufferSize, 8);
-            FUZ_CHECKTEST(r==0, "LZ4_compress_fast_extState() failed"); }
+            FUZ_CHECKTEST(r==0, "LZ4_compress_fast_extState() failed");
+
+            FUZ_DISPLAYTEST("test LZ4_compress_fast_extState() with a too small destination buffer (must fail)");
+            {   int const r2 = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, r-1, 8);
+                FUZ_CHECKTEST(r2!=0, "LZ4_compress_fast_extState() should have failed");
+            }
+
+            FUZ_DISPLAYTEST("test LZ4_compress_destSize_extState() with too small dest buffer (must succeed, compress less than full input)");
+            {   int inputSize = blockSize;
+                int const r3 = LZ4_compress_destSize_extState(stateLZ4, block, compressedBuffer, &inputSize, r-1, 8);
+                FUZ_CHECKTEST(r3==0, "LZ4_compress_destSize_extState() failed");
+                FUZ_CHECKTEST(inputSize>=blockSize, "LZ4_compress_destSize_extState() should consume less than full input");
+            }
+        }
 
         /* Test compression using fast reset external state*/
-        FUZ_DISPLAYTEST();
+        FUZ_DISPLAYTEST("test LZ4_compress_fast_extState_fastReset()");
         {   int const r = LZ4_compress_fast_extState_fastReset(stateLZ4, block, compressedBuffer, blockSize, (int)compressedBufferSize, 8);
             FUZ_CHECKTEST(r==0, "LZ4_compress_fast_extState_fastReset() failed"); }
 
@@ -495,12 +509,12 @@
         {   char* const cBuffer_exact = (char*)malloc((size_t)compressedSize);
             assert(cBuffer_exact != NULL);
             assert(compressedSize <= (int)compressedBufferSize);
-#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
+#if defined(_MSC_VER) && (_MSC_VER <= 1936) /* MSVC 2022 ver 17.6 or earlier */
 #  pragma warning(push)
 #  pragma warning(disable : 6385) /* lz4\tests\fuzzer.c(497): warning C6385: Reading invalid data from 'compressedBuffer'. */
 #endif
             memcpy(cBuffer_exact, compressedBuffer, compressedSize);
-#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
+#if defined(_MSC_VER) && (_MSC_VER <= 1936) /* MSVC 2022 ver 17.6 or earlier */
 #  pragma warning(pop)
 #endif
 
@@ -709,7 +723,7 @@
             {   int const cSize = LZ4_compress_default(block, compressedBuffer, blockSize, compressedSize-missingBytes);
                 FUZ_CHECKTEST(cSize, "LZ4_compress_default should have failed (output buffer too small by %i byte)", missingBytes);
             }
-            FUZ_CHECKTEST(compressedBuffer[compressedSize-missingBytes], "LZ4_compress_default overran output buffer ! (%i missingBytes)", missingBytes)
+            FUZ_CHECKTEST(compressedBuffer[compressedSize-missingBytes], "LZ4_compress_default overran output buffer ! (%i missingBytes)", missingBytes);
         }
 
         /* Test HC compression with missing bytes into output buffer => must fail */
@@ -721,7 +735,7 @@
             {   int const hcSize = LZ4_compress_HC(block, compressedBuffer, blockSize, HCcompressedSize-missingBytes, compressionLevel);
                 FUZ_CHECKTEST(hcSize, "LZ4_compress_HC should have failed (output buffer too small by %i byte)", missingBytes);
             }
-            FUZ_CHECKTEST(compressedBuffer[HCcompressedSize-missingBytes], "LZ4_compress_HC overran output buffer ! (%i missingBytes)", missingBytes)
+            FUZ_CHECKTEST(compressedBuffer[HCcompressedSize-missingBytes], "LZ4_compress_HC overran output buffer ! (%i missingBytes)", missingBytes);
         }
 
 
@@ -919,8 +933,8 @@
         FUZ_DISPLAYTEST("LZ4_compress_HC_continue with an external dictionary");
         dict -= (FUZ_rand(&randState) & 7);    /* even bigger separation */
         if (dict < (char*)CNBuffer) dict = (char*)CNBuffer;
-        LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
         LZ4_setCompressionLevel (LZ4dictHC, compressionLevel);
+        LZ4_loadDictHC(LZ4dictHC, dict, dictSize);
         blockContinueCompressedSize = LZ4_compress_HC_continue(LZ4dictHC, block, compressedBuffer, blockSize, (int)compressedBufferSize);
         FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue failed");
         FUZ_CHECKTEST(LZ4dictHC->internal_donotuse.dirty, "Context should be clean");
@@ -1016,7 +1030,7 @@
             decodedBuffer[consumedSize] = 0;
             ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, consumedSize, dict, dictSize);
             FUZ_CHECKTEST(ret != consumedSize, "LZ4_decompress_safe_usingDict regenerated %i bytes (%i expected)", ret, consumedSize);
-            FUZ_CHECKTEST(decodedBuffer[consumedSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size")
+            FUZ_CHECKTEST(decodedBuffer[consumedSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size");
             {   U32 const crcSrc = XXH32(block, (size_t)consumedSize, 0);
                 U32 const crcDst = XXH32(decodedBuffer, (size_t)consumedSize, 0);
                 if (crcSrc!=crcDst) {
@@ -1041,9 +1055,9 @@
     bytes += !bytes;   /* avoid division by 0 */
     printf("\r%7u /%7u   - ", cycleNb, nbCycles);
     printf("all tests completed successfully \n");
-    printf("compression ratio: %0.3f%%\n", (double)cbytes/bytes*100);
-    printf("HC compression ratio: %0.3f%%\n", (double)hcbytes/bytes*100);
-    printf("ratio with dict: %0.3f%%\n", (double)ccbytes/bytes*100);
+    printf("compression ratio: %0.3f%%\n", (double)cbytes/(double)bytes*100);
+    printf("HC compression ratio: %0.3f%%\n", (double)hcbytes/(double)bytes*100);
+    printf("ratio with dict: %0.3f%%\n", (double)ccbytes/(double)bytes*100);
 
     /* release memory */
     free(CNBuffer);
diff --git a/tests/loremOut.c b/tests/loremOut.c
new file mode 100644
index 0000000..a542e70
--- /dev/null
+++ b/tests/loremOut.c
@@ -0,0 +1,62 @@
+/*
+    lorem.c - lorem ipsum generator to stdout
+    Copyright (C) Yann Collet 2024
+
+    GPL v2 License
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+    You can contact the author at :
+   - LZ4 source repository : https://github.com/lz4/lz4
+   - Public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/* Implementation notes:
+ * Generates a stream of Lorem ipsum paragraphs to stdout,
+ * up to the requested size, which can be very large (> 4 GB).
+ * Note that, beyond 1 paragraph, this generator produces
+ * a different content than LOREM_genBuffer (even when using same seed).
+ */
+
+#include "platform.h"  /* Compiler options, SET_BINARY_MODE */
+#include "loremOut.h"
+#include "lorem.h"     /* LOREM_genBlock */
+#include <stdio.h>
+#include <assert.h>
+
+
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#define LOREM_BLOCKSIZE (2 << 10)
+void LOREM_genOut(unsigned long long size, unsigned seed)
+{
+  char buff[LOREM_BLOCKSIZE] = {0};
+  unsigned long long total = 0;
+  size_t genBlockSize = (size_t)MIN(size, LOREM_BLOCKSIZE);
+
+  /* init */
+  SET_BINARY_MODE(stdout);
+
+  /* Generate Ipsum text, one paragraph at a time */
+  while (total < size) {
+    size_t generated = LOREM_genBlock(buff, genBlockSize, seed++, total == 0, 0);
+    assert(generated <= genBlockSize);
+    total += generated;
+    assert(total <= size);
+    fwrite(buff, 1, generated, stdout); /* note: should check potential write error */
+    if (size - total < genBlockSize)
+      genBlockSize = (size_t)(size - total);
+  }
+  assert(total == size);
+}
diff --git a/tests/loremOut.h b/tests/loremOut.h
new file mode 100644
index 0000000..17fef43
--- /dev/null
+++ b/tests/loremOut.h
@@ -0,0 +1,30 @@
+/*
+    loremOut.h - lorem ipsum generator to stdout
+    Copyright (C) Yann Collet 2024
+
+    GPL v2 License
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+    You can contact the author at :
+   - LZ4 source repository : https://github.com/lz4/lz4
+   - Public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+
+/* LOREM_genOut():
+ * Generate @size bytes of compressible data using lorem ipsum generator into stdout.
+ */
+void LOREM_genOut(unsigned long long size, unsigned seed);
diff --git a/tests/test-lz4-abi.py b/tests/test-lz4-abi.py
index 0c8fd05..88661ac 100644
--- a/tests/test-lz4-abi.py
+++ b/tests/test-lz4-abi.py
@@ -7,6 +7,7 @@
 # GPL v2 License
 #
 
+import argparse
 import glob
 import subprocess
 import filecmp
@@ -17,15 +18,24 @@
 
 repo_url = 'https://github.com/lz4/lz4.git'
 tmp_dir_name = 'tests/abiTests'
-env_flags = ' ' # '-j MOREFLAGS="-g -O0 -fsanitize=address"'
+env_flags = ' ' # '-j CFLAGS="-g -O0 -fsanitize=address"'
 make_cmd = 'make'
 git_cmd = 'git'
 test_dat_src = ['README.md']
 head = 'v999'
 
+parser = argparse.ArgumentParser()
+parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+args = parser.parse_args()
+
+def debug_message(msg):
+    if args.verbose:
+        print(msg)
+
 def proc(cmd_args, pipe=True, env=False):
     if env == False:
         env = os.environ.copy()
+    debug_message("Executing command {} with env {}".format(cmd_args, env))
     if pipe:
         s = subprocess.Popen(cmd_args,
                              stdout=subprocess.PIPE,
@@ -33,18 +43,22 @@
                              env = env)
     else:
         s = subprocess.Popen(cmd_args, env = env)
-    r = s.communicate()
+    stdout_data, stderr_data = s.communicate()
     if s.poll() != 0:
-        print(' s.poll() = ', s.poll())
+        print('Error Code:', s.poll())
+        print('Standard Error:', stderr_data.decode())
         sys.exit(1)
-    return r
+    return stdout_data, stderr_data
 
 def make(args, pipe=True, env=False):
     if env == False:
         env = os.environ.copy()
-        # we want the address sanitizer for abi tests
-        env["MOREFLAGS"] = "-fsanitize=address"
-    return proc([make_cmd] + ['-j'] + ['V=1'] + args, pipe, env)
+    # we want the address sanitizer for abi tests
+    if 'CFLAGS' in env:
+        env["CFLAGS"] += " -fsanitize=address"
+    if 'LDFLAGS' in env:
+        env["LDFLAGS"] += " -fsanitize=address"
+    return proc([make_cmd] + ['-j'] + ['V=1'] + ['DEBUGFLAGS='] + args, pipe, env)
 
 def git(args, pipe=True):
     return proc([git_cmd] + args, pipe)
@@ -61,6 +75,9 @@
         return hashlib.sha1(f.read()).hexdigest()
 
 if __name__ == '__main__':
+    if sys.platform == "darwin":
+        print("!!! Warning: this test is not validated for macos !!!")
+
     error_code = 0
     base_dir = os.getcwd() + '/..'           # /path/to/lz4
     tmp_dir = base_dir + '/' + tmp_dir_name  # /path/to/lz4/tests/versionsTest
@@ -81,7 +98,8 @@
     print(tags)
 
     # loop across architectures
-    for march in ['-m64', '-m32', '-mx32']:
+    # note : '-mx32' was removed, because some CI environment (GA) do not support x32 well
+    for march in ['-m64', '-m32']:
         print(' ')
         print('=====================================')
         print('Testing architecture ' + march);
@@ -105,8 +123,7 @@
                 os.chdir(lib_dir)
             make(['clean'])
             build_env = os.environ.copy()
-            build_env["CFLAGS"] = march
-            build_env["MOREFLAGS"] = "-fsanitize=address"
+            build_env["CFLAGS"] = "-O1 " + march
             make(['liblz4'], env=build_env)
 
         print(' ')
@@ -116,11 +133,10 @@
         os.chdir(test_dir)
         # Start with matching version : should be no problem
         build_env = os.environ.copy()
-        build_env["CFLAGS"] = march
+        # we use asan to detect any out-of-bound read or write
+        build_env["CFLAGS"] = "-O1 " + march
         build_env["LDFLAGS"] = "-L../lib"
         build_env["LDLIBS"] = "-llz4"
-        # we use asan to detect any out-of-bound read or write
-        build_env["MOREFLAGS"] = "-fsanitize=address"
         if os.path.isfile('abiTest'):
             os.remove('abiTest')
         make(['abiTest'], env=build_env, pipe=False)
@@ -148,13 +164,12 @@
             build_env = os.environ.copy()
             if tag != head:
                 build_env["CPPFLAGS"] = '-IabiTests/{}/lib'.format(tag)
-                build_env["LDFLAGS"] = '-LabiTests/{}/lib'.format(tag)
+                build_env["LDFLAGS"]  = '-LabiTests/{}/lib'.format(tag)
             else:
                 build_env["CPPFLAGS"] = '-I../lib'
-                build_env["LDFLAGS"] = '-L../lib'
-            build_env["LDLIBS"] = "-llz4"
-            build_env["CFLAGS"] = march
-            build_env["MOREFLAGS"] = "-fsanitize=address"
+                build_env["LDFLAGS"]  = '-L../lib'
+            build_env["LDLIBS"]  = "-llz4"
+            build_env["CFLAGS"]  = "-O1 " + march
             os.remove('abiTest')
             make(['abiTest'], pipe=False, env=build_env)
 
diff --git a/tests/test-lz4-basic.sh b/tests/test-lz4-basic.sh
new file mode 100755
index 0000000..7e40975
--- /dev/null
+++ b/tests/test-lz4-basic.sh
@@ -0,0 +1,85 @@
+#!/bin/sh
+
+FPREFIX="tmp-tlb"
+
+set -e
+
+remove () {
+    rm -rf $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -g0       | lz4 -v     | lz4 -t
+datagen -g16KB    | lz4 -9     | lz4 -t
+datagen -g20KB > $FPREFIX-dg20k
+lz4 < $FPREFIX-dg20k | lz4 -d > $FPREFIX-dec
+diff -q $FPREFIX-dg20k $FPREFIX-dec
+lz4 --no-frame-crc < $FPREFIX-dg20k | lz4 -d > $FPREFIX-dec
+diff -q $FPREFIX-dg20k $FPREFIX-dec
+datagen           | lz4 -BI    | lz4 -t
+datagen           | lz4 --no-crc | lz4 -t
+datagen -g6M -P99 | lz4 -9BD   | lz4 -t
+datagen -g17M     | lz4 -9v    | lz4 -qt
+datagen -g33M     | lz4 --no-frame-crc | lz4 -t
+datagen -g256MB   | lz4 -vqB4D | lz4 -t --no-crc
+echo "hello world" > $FPREFIX-hw
+lz4 --rm -f $FPREFIX-hw $FPREFIX-hw.lz4
+test ! -f $FPREFIX-hw                   # must fail (--rm)
+test   -f $FPREFIX-hw.lz4
+lz4 -d --rm -f $FPREFIX-hw.lz4
+test ! -f $FPREFIX-hw.lz4
+lz4 --rm -f $FPREFIX-hw > /dev/null
+test   -f $FPREFIX-hw.lz4               # no more implicit stdout
+lz4cat $FPREFIX-hw.lz4 | grep "hello world"
+unlz4 --rm $FPREFIX-hw.lz4 $FPREFIX-hw
+test   -f $FPREFIX-hw
+test ! -f $FPREFIX-hw.lz4               # must fail (--rm)
+test ! -f $FPREFIX-hw.lz4.lz4           # must fail (unlz4)
+lz4cat $FPREFIX-hw                      # pass-through mode
+test   -f $FPREFIX-hw
+test ! -f $FPREFIX-hw.lz4               # must fail (lz4cat)
+lz4 $FPREFIX-hw $FPREFIX-hw.lz4         # creates $FPREFIX-hw.lz4
+lz4cat < $FPREFIX-hw.lz4 > ${FPREFIX}3  # checks lz4cat works with stdin (#285)
+diff -q $FPREFIX-hw ${FPREFIX}3
+lz4cat < $FPREFIX-hw > ${FPREFIX}2      # checks lz4cat works in pass-through mode
+diff -q $FPREFIX-hw ${FPREFIX}2
+cp $FPREFIX-hw ./-d
+lz4 --rm -- -d -d.lz4                   # compresses ./d into ./-d.lz4
+test   -f ./-d.lz4
+test ! -f ./-d
+mv ./-d.lz4 ./-z
+lz4 -d --rm -- -z ${FPREFIX}4           # uncompresses ./-z into $FPREFIX4
+test ! -f ./-z
+diff -q $FPREFIX-hw ${FPREFIX}4
+lz4 ${FPREFIX}2 ${FPREFIX}3 ${FPREFIX}4 && exit 1  # must fail: refuse to handle 3+ file names
+mkdir -p ${FPREFIX}-dir
+lz4 ${FPREFIX}-dir && exit 1          # must fail: refuse to compress directory
+test ! -f ${FPREFIX}-dir.lz4          # must not create artifact (#1211)
+lz4 -f $FPREFIX-hw                    # create $FPREFIX-hw.lz4, for next tests
+lz4 --list $FPREFIX-hw.lz4            # test --list on valid single-frame file
+lz4 --list < $FPREFIX-hw.lz4          # test --list from stdin (file only)
+cat $FPREFIX-hw >> $FPREFIX-hw.lz4
+lz4 -f $FPREFIX-hw.lz4 && exit 1      # uncompress valid frame followed by invalid data (must fail now)
+lz4 -BX $FPREFIX-hw -c -q | lz4 -tv   # test block checksum
+# datagen -g20KB generates the same file every single time
+# cannot save output of datagen -g20KB as input file to lz4 because the following shell commands are run before datagen -g20KB
+test "$(datagen -g20KB | lz4 -c --fast | wc -c)" -lt "$(datagen -g20KB | lz4 -c --fast=9 | wc -c)" # -1 vs -9
+test "$(datagen -g20KB | lz4 -c -1 | wc -c)" -lt "$(datagen -g20KB| lz4 -c --fast=1 | wc -c)" # 1 vs -1
+test "$(datagen -g20KB | lz4 -c --fast=1 | wc -c)" -eq "$(datagen -g20KB| lz4 -c --fast| wc -c)" # checks default fast compression is -1
+lz4 -c --fast=0 $FPREFIX-dg20K && exit 1  # lz4 should fail when fast=0
+lz4 -c --fast=-1 $FPREFIX-dg20K && exit 1 # lz4 should fail when fast=-1
+# Multithreading commands
+datagen -g16M | lz4 -T2 | lz4 -t
+datagen -g16M | lz4 --threads=2 | lz4 -t
+# High --fast values can result in out-of-bound dereferences #876
+datagen -g1M | lz4 -c --fast=999999999 > $FPREFIX-trash
+# Test for #596
+echo "TEST" > $FPREFIX-test
+lz4 -m $FPREFIX-test
+lz4 $FPREFIX-test.lz4 $FPREFIX-test2
+diff -q $FPREFIX-test $FPREFIX-test2
+# bug #1374
+datagen -g4194302 | lz4 -B4 -c > $FPREFIX-test3
diff --git a/tests/test-lz4-contentSize.sh b/tests/test-lz4-contentSize.sh
new file mode 100755
index 0000000..b2d8e1b
--- /dev/null
+++ b/tests/test-lz4-contentSize.sh
@@ -0,0 +1,27 @@
+#!/bin/sh
+
+FPREFIX="tmp-lzc"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -g15M > $FPREFIX
+lz4 -v $FPREFIX -c | lz4 -t
+lz4 -v --content-size $FPREFIX -c | lz4 -d > $FPREFIX-dup
+diff $FPREFIX $FPREFIX-dup
+lz4 -f $FPREFIX -c > $FPREFIX.lz4 # compressed with content size
+lz4 --content-size $FPREFIX -c > $FPREFIX-wcz.lz4
+diff $FPREFIX.lz4 $FPREFIX-wcz.lz4 && exit 1 # must differ, due to content size
+lz4 --content-size < $FPREFIX > $FPREFIX-wcz2.lz4 # can determine content size because stdin is just a file
+diff $FPREFIX-wcz.lz4 $FPREFIX-wcz2.lz4  # both must contain content size
+cat $FPREFIX | lz4 > $FPREFIX-ncz.lz4
+diff $FPREFIX.lz4 $FPREFIX-ncz.lz4  # both don't have content size
+cat $FPREFIX | lz4 --content-size > $FPREFIX-ncz2.lz4 # can't determine content size
+diff $FPREFIX.lz4 $FPREFIX-ncz2.lz4  # both don't have content size
diff --git a/tests/test-lz4-dict.sh b/tests/test-lz4-dict.sh
new file mode 100755
index 0000000..a1462ab
--- /dev/null
+++ b/tests/test-lz4-dict.sh
@@ -0,0 +1,46 @@
+#!/bin/sh
+
+FPREFIX="tmp-dict"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -g16KB > $FPREFIX
+datagen -g32KB > $FPREFIX-sample-32k
+< $FPREFIX-sample-32k lz4 -D $FPREFIX | lz4 -dD $FPREFIX | diff - $FPREFIX-sample-32k
+datagen -g16MB > $FPREFIX-sample-16m
+lz4 -v -B5 $FPREFIX-sample-16m -D $FPREFIX -c | lz4 -d -D $FPREFIX | diff - $FPREFIX-sample-16m
+
+# Check dictionary compression efficiency
+size_dict=$( lz4 -3 -B4 $FPREFIX-sample-16m -D $FPREFIX -c | wc -c)
+size_nodict=$( lz4 -3 -B4 $FPREFIX-sample-16m -c | wc -c)
+if [ "$size_dict" -lt "$size_nodict" ]; then
+    echo "Test Passed: dictionary is effective."
+else
+    echo "Test Failed: dictionary wasn't effective."
+    exit 1
+fi
+
+touch $FPREFIX-sample-0
+< $FPREFIX-sample-0 lz4 -D $FPREFIX | lz4 -dD $FPREFIX | diff - $FPREFIX-sample-0
+
+< $FPREFIX-sample-32k lz4 -D $FPREFIX-sample-0 | lz4 -dD $FPREFIX-sample-0 | diff - $FPREFIX-sample-32k
+< $FPREFIX-sample-0 lz4 -D $FPREFIX-sample-0 | lz4 -dD $FPREFIX-sample-0 | diff - $FPREFIX-sample-0
+lz4 -bi0 -D $FPREFIX $FPREFIX-sample-32k $FPREFIX-sample-32k
+
+echo "---- test lz4 dictionary loading ----"
+datagen -g128KB > $FPREFIX-data-128KB
+set -e; \
+for l in 0 1 4 128 32767 32768 32769 65535 65536 65537 98303 98304 98305 131071 131072 131073; do \
+    datagen -g$$l > $FPREFIX-$$l; \
+    dd if=$FPREFIX-$$l of=$FPREFIX-$$l-tail bs=1 count=65536 skip=$((l > 65536 ? l - 65536 : 0)); \
+    < $FPREFIX-$$l      lz4 -D stdin $FPREFIX-data-128KB -c | lz4 -dD $FPREFIX-$$l-tail | diff - $FPREFIX-data-128KB; \
+    < $FPREFIX-$$l-tail lz4 -D stdin $FPREFIX-data-128KB -c | lz4 -dD $FPREFIX-$$l      | diff - $FPREFIX-data-128KB; \
+done
diff --git a/tests/test-lz4-fast-hugefile.sh b/tests/test-lz4-fast-hugefile.sh
new file mode 100755
index 0000000..5820478
--- /dev/null
+++ b/tests/test-lz4-fast-hugefile.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+FPREFIX="tmp-lfh"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -g6GB    | lz4 -vB5 | lz4 -qt
+# test large file size [2-4] GB
+datagen -g3G -P100 | lz4 -vv | lz4 --decompress --force --sparse - ${FPREFIX}1
+ls -ls ${FPREFIX}1
+datagen -g3G -P100 | lz4 --quiet --content-size | lz4 --verbose --decompress --force --sparse - ${FPREFIX}2
+ls -ls ${FPREFIX}2
+diff -s ${FPREFIX}1 ${FPREFIX}2
diff --git a/tests/test-lz4-frame-concatenation.sh b/tests/test-lz4-frame-concatenation.sh
new file mode 100755
index 0000000..94165c1
--- /dev/null
+++ b/tests/test-lz4-frame-concatenation.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+FPREFIX="tmp-lfc"
+
+set -e
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+echo > $FPREFIX-empty
+echo hi > $FPREFIX-nonempty
+cat $FPREFIX-nonempty $FPREFIX-empty $FPREFIX-nonempty > $FPREFIX-src
+lz4 -zq $FPREFIX-empty -c > $FPREFIX-empty.lz4
+lz4 -zq $FPREFIX-nonempty -c > $FPREFIX-nonempty.lz4
+cat $FPREFIX-nonempty.lz4 $FPREFIX-empty.lz4 $FPREFIX-nonempty.lz4 > $FPREFIX-concat.lz4
+lz4 -d $FPREFIX-concat.lz4 -c > $FPREFIX-result
+cmp $FPREFIX-src $FPREFIX-result
diff --git a/tests/test-lz4-list.py b/tests/test-lz4-list.py
index fe11682..a298fe9 100644
--- a/tests/test-lz4-list.py
+++ b/tests/test-lz4-list.py
@@ -15,7 +15,7 @@
 TEMP = tempfile.gettempdir()
 
 
-class NVerboseFileInfo(object):
+class NVerboseFileInfo:
     def __init__(self, line_in):
         self.line = line_in
         splitlines = line_in.split()
@@ -92,7 +92,7 @@
                 self.assertEqual(nvinfo.uncompressed, to_human(nvinfo.exp_unc_size), nvinfo.line)
 
 
-class VerboseFileInfo(object):
+class VerboseFileInfo:
     def __init__(self, lines):
         # Parse lines
         self.frame_list = []
@@ -138,24 +138,11 @@
         self.cvinfo.file_frame_map = concat_file_list
         self.cvinfo.compressed_size = os.path.getsize(f"{TEMP}/test_list_concat-all.lz4")
 
-    def test_filename(self):
-        for i, vinfo in enumerate(self.vinfo_list):
-            self.assertRegex(vinfo.filename, f"^test_list_.*({i + 1}/{len(self.vinfo_list)})".format(i + 1, len(self.vinfo_list)))
-
     def test_frame_number(self):
         for vinfo in self.vinfo_list:
             for i, frame_info in enumerate(vinfo.frame_list):
                 self.assertEqual(frame_info["frame"], str(i + 1), frame_info["line"])
 
-    def test_frame_type(self):
-        for i, frame_info in enumerate(self.cvinfo.frame_list):
-            if "-lz4f-" in self.cvinfo.file_frame_map[i]:
-                self.assertEqual(self.cvinfo.frame_list[i]["type"], "LZ4Frame", self.cvinfo.frame_list[i]["line"])
-            elif "-legc-" in self.cvinfo.file_frame_map[i]:
-                self.assertEqual(self.cvinfo.frame_list[i]["type"], "LegacyFrame", self.cvinfo.frame_list[i]["line"])
-            elif "-skip-" in self.cvinfo.file_frame_map[i]:
-                self.assertEqual(self.cvinfo.frame_list[i]["type"], "SkippableFrame", self.cvinfo.frame_list[i]["line"])
-
     def test_block(self):
         for i, frame_info in enumerate(self.cvinfo.frame_list):
             if "--BD" in self.cvinfo.file_frame_map[i]:
@@ -168,15 +155,6 @@
             if "-lz4f-" in self.cvinfo.file_frame_map[i] and "--no-frame-crc" not in self.cvinfo.file_frame_map[i]:
                 self.assertEqual(self.cvinfo.frame_list[i]["checksum"], "XXH32", self.cvinfo.frame_list[i]["line"])
 
-    def test_compressed(self):
-        total = 0
-        for i, frame_info in enumerate(self.cvinfo.frame_list):
-            if "-2f-" not in self.cvinfo.file_frame_map[i]:
-                expected_size = os.path.getsize(self.cvinfo.file_frame_map[i])
-                self.assertEqual(self.cvinfo.frame_list[i]["compressed"], str(expected_size), self.cvinfo.frame_list[i]["line"])
-            total += int(self.cvinfo.frame_list[i]["compressed"])
-        self.assertEqual(total, self.cvinfo.compressed_size, f"Expected total sum ({total}) to match {self.cvinfo.filename} filesize")
-
     def test_uncompressed(self):
         for i, frame_info in enumerate(self.cvinfo.frame_list):
             ffm = self.cvinfo.file_frame_map[i]
@@ -227,7 +205,7 @@
         if stderr_lines and not print_output and print_error:
             print(stderr_lines)
         errout(f"Failed to run: {command}, {stdout_lines + stderr_lines}\n")
-    return (stdout_lines + stderr_lines).splitlines()
+    return (stdout_lines).splitlines()
 
 
 def cleanup(silent=False):
diff --git a/tests/test-lz4-multiple-legacy.sh b/tests/test-lz4-multiple-legacy.sh
new file mode 100755
index 0000000..e9dc0ec
--- /dev/null
+++ b/tests/test-lz4-multiple-legacy.sh
@@ -0,0 +1,51 @@
+#!/bin/sh
+
+FPREFIX="tmp-lml"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -s1        > "${FPREFIX}1" 2> $FPREFIX-trash
+datagen -s2 -g100K > "${FPREFIX}2" 2> $FPREFIX-trash
+datagen -s3 -g200K > "${FPREFIX}3" 2> $FPREFIX-trash
+# compress multiple files using legacy format: one .lz4 per source file
+lz4 -f -l -m $FPREFIX*
+test -f ${FPREFIX}1.lz4
+test -f ${FPREFIX}2.lz4
+test -f ${FPREFIX}3.lz4
+# decompress multiple files compressed using legacy format: one output file per .lz4
+mv ${FPREFIX}1 ${FPREFIX}1-orig
+mv ${FPREFIX}2 ${FPREFIX}2-orig
+mv ${FPREFIX}3 ${FPREFIX}3-orig
+lz4 -d -f -m $FPREFIX*.lz4
+lz4 -l -d -f -m $FPREFIX*.lz4 # -l mustn't impact -d option
+cmp ${FPREFIX}1 ${FPREFIX}1-orig   # must be identical
+cmp ${FPREFIX}2 ${FPREFIX}2-orig
+cmp ${FPREFIX}3 ${FPREFIX}3-orig
+# compress multiple files into stdout using legacy format
+cat ${FPREFIX}1.lz4 ${FPREFIX}2.lz4 ${FPREFIX}3.lz4 > $FPREFIX-concat1
+rm -f $FPREFIX*.lz4
+lz4 -l -m ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3 -c > $FPREFIX-concat2
+test ! -f ${FPREFIX}1.lz4  # must not create .lz4 artefact
+cmp $FPREFIX-concat1 $FPREFIX-concat2  # must be equivalent
+# # # decompress multiple files into stdout using legacy format
+rm $FPREFIX-concat1 $FPREFIX-concat2
+lz4 -l -f -m ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3   # generate .lz4 to decompress
+cat ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3 > ${FPREFIX}-concat1   # create concatenated reference
+rm ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3
+lz4 -d -m ${FPREFIX}1.lz4 ${FPREFIX}2.lz4 ${FPREFIX}3.lz4 -c > $FPREFIX-concat2
+lz4 -d -l -m ${FPREFIX}1.lz4 ${FPREFIX}2.lz4 ${FPREFIX}3.lz4 -c > $FPREFIX-concat2 # -l mustn't impact option -d
+test ! -f ${FPREFIX}1  # must not create file artefact
+cmp $FPREFIX-concat1 $FPREFIX-concat2  # must be equivalent
+# # # compress multiple files, one of which is absent (must fail)
+rm -f $FPREFIX-concat2.lz4
+lz4 -f -l -m $FPREFIX-concat1 notHere-legacy $FPREFIX-concat2 && exit 1 # must fail : notHere-legacy not present
+test -f $FPREFIX-concat2.lz4 # notHere was a non-blocking error, concat2.lz4 should be present
+true
diff --git a/tests/test-lz4-multiple.sh b/tests/test-lz4-multiple.sh
new file mode 100755
index 0000000..3c854d4
--- /dev/null
+++ b/tests/test-lz4-multiple.sh
@@ -0,0 +1,58 @@
+#!/bin/sh
+
+FPREFIX="tmp-tml"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -s1        > ${FPREFIX}1 2> $FPREFIX-trash
+datagen -s2 -g100K > ${FPREFIX}2 2> $FPREFIX-trash
+datagen -s3 -g200K > ${FPREFIX}3 2> $FPREFIX-trash
+# compress multiple files : one .lz4 per source file
+lz4 -f -m $FPREFIX*
+test -f ${FPREFIX}1.lz4
+test -f ${FPREFIX}2.lz4
+test -f ${FPREFIX}3.lz4
+# decompress multiple files : one output file per .lz4
+mv ${FPREFIX}1 ${FPREFIX}1-orig
+mv ${FPREFIX}2 ${FPREFIX}2-orig
+mv ${FPREFIX}3 ${FPREFIX}3-orig
+lz4 -d -f -m $FPREFIX*.lz4
+cmp ${FPREFIX}1 ${FPREFIX}1-orig   # must be identical
+cmp ${FPREFIX}2 ${FPREFIX}2-orig
+cmp ${FPREFIX}3 ${FPREFIX}3-orig
+# compress multiple files into stdout
+cat ${FPREFIX}1.lz4 ${FPREFIX}2.lz4 ${FPREFIX}3.lz4 > $FPREFIX-concat1
+rm $FPREFIX*.lz4
+lz4 -m ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3 -c > $FPREFIX-concat2
+test ! -f ${FPREFIX}1.lz4  # must not create .lz4 artefact
+cmp $FPREFIX-concat1 $FPREFIX-concat2  # must be equivalent
+# decompress multiple files into stdout
+rm $FPREFIX-concat1 $FPREFIX-concat2
+lz4 -f -m ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3   # generate .lz4 to decompress
+cat ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3 > $FPREFIX-concat1   # create concatenated reference
+rm ${FPREFIX}1 ${FPREFIX}2 ${FPREFIX}3
+lz4 -d -m ${FPREFIX}1.lz4 ${FPREFIX}2.lz4 ${FPREFIX}3.lz4 -c > $FPREFIX-concat2
+test ! -f ${FPREFIX}1  # must not create file artefact
+cmp $FPREFIX-concat1 $FPREFIX-concat2  # must be equivalent
+# compress multiple files, one of which is absent (must fail)
+lz4 -f -m $FPREFIX-concat1 notHere $FPREFIX-concat2 && exit 1 # must fail : notHere not present
+# test lz4-compressed file
+rm $FPREFIX-concat1 $FPREFIX-concat2
+lz4 -tm $FPREFIX-concat1.lz4
+# ensure the test doesn't create artifact
+test ! -f $FPREFIX-concat1  # must not create file artefact
+# test multiple lz4-compressed file
+lz4 -tm $FPREFIX-concat1.lz4 $FPREFIX-concat2.lz4
+test ! -f $FPREFIX-concat1  # must not create file artefact
+test ! -f $FPREFIX-concat2  # must not create file artefact
+# test multiple lz4 files, one of which is absent (must fail)
+lz4 -tm $FPREFIX-concat1.lz4 notHere.lz4 $FPREFIX-concat2.lz4 && exit 1
+true
diff --git a/tests/test-lz4-opt-parser.sh b/tests/test-lz4-opt-parser.sh
new file mode 100755
index 0000000..5b8d1dc
--- /dev/null
+++ b/tests/test-lz4-opt-parser.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+set -e
+set -x
+
+datagen -g16KB      | lz4 -12      | lz4 -t
+datagen -P10        | lz4 -12B4    | lz4 -t
+datagen -g256K      | lz4 -12B4D   | lz4 -t
+datagen -g512K -P25 | lz4 -12BD    | lz4 -t
+datagen -g1M        | lz4 -12B5    | lz4 -t
+datagen -g1M -s2    | lz4 -12B4D   | lz4 -t
+datagen -g2M -P99   | lz4 -11B4D   | lz4 -t
+datagen -g4M        | lz4 -11vq    | lz4 -qt
+datagen -g8M        | lz4 -11B4    | lz4 -t
+datagen -g16M -P90  | lz4 -11B5    | lz4 -t
+datagen -g32M -P10  | lz4 -11B5D   | lz4 -t
diff --git a/tests/test-lz4-skippable.sh b/tests/test-lz4-skippable.sh
new file mode 100755
index 0000000..e34a33f
--- /dev/null
+++ b/tests/test-lz4-skippable.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+
+SKIPFILE="goldenSamples/skip.bin"
+FPREFIX="tmp-lsk"
+
+set -e
+
+remove () {
+    rm "$FPREFIX"*
+}
+
+trap remove EXIT
+
+set -x
+
+lz4 -dc $SKIPFILE
+lz4 -dc < $SKIPFILE
+printf "Hello from Valid Frame!\n" | lz4 -c > $FPREFIX.lz4
+cat $SKIPFILE $FPREFIX.lz4 $SKIPFILE | lz4 -dc
diff --git a/tests/test-lz4-sparse.sh b/tests/test-lz4-sparse.sh
new file mode 100755
index 0000000..99297ff
--- /dev/null
+++ b/tests/test-lz4-sparse.sh
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+FPREFIX="tmp-tls"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+datagen -g5M  -P100 > ${FPREFIX}dg5M
+lz4 -B4D ${FPREFIX}dg5M -c | lz4 -dv --sparse > ${FPREFIX}cB4
+diff -s ${FPREFIX}dg5M ${FPREFIX}cB4
+lz4 -B5D ${FPREFIX}dg5M -c | lz4 -dv --sparse > ${FPREFIX}cB5
+diff -s ${FPREFIX}dg5M ${FPREFIX}cB5
+lz4 -B6D ${FPREFIX}dg5M -c | lz4 -dv --sparse > ${FPREFIX}cB6
+diff -s ${FPREFIX}dg5M ${FPREFIX}cB6
+lz4 -B7D ${FPREFIX}dg5M -c | lz4 -dv --sparse > ${FPREFIX}cB7
+diff -s ${FPREFIX}dg5M ${FPREFIX}cB7
+lz4 ${FPREFIX}dg5M -c | lz4 -dv --no-sparse > ${FPREFIX}nosparse
+diff -s ${FPREFIX}dg5M ${FPREFIX}nosparse
+ls -ls $FPREFIX*
+datagen -s1 -g1200007 -P100 | lz4 | lz4 -dv --sparse > ${FPREFIX}odd   # Odd size file (to generate non-full last block)
+datagen -s1 -g1200007 -P100 | diff -s - ${FPREFIX}odd
+ls -ls ${FPREFIX}odd
+rm $FPREFIX*
+printf "\n Compatibility with Console :"
+echo "Hello World 1 !" | lz4 | lz4 -d -c
+echo "Hello World 2 !" | lz4 | lz4 -d | cat
+echo "Hello World 3 !" | lz4 --no-frame-crc | lz4 -d -c
+printf "\n Compatibility with Append :"
+datagen -P100 -g1M > ${FPREFIX}dg1M
+cat ${FPREFIX}dg1M ${FPREFIX}dg1M > ${FPREFIX}2M
+lz4 -B5 -v ${FPREFIX}dg1M ${FPREFIX}c
+lz4 -d -v ${FPREFIX}c ${FPREFIX}r
+lz4 -d -v ${FPREFIX}c -c >> ${FPREFIX}r
+ls -ls $FPREFIX*
+diff ${FPREFIX}2M ${FPREFIX}r
diff --git a/tests/test-lz4-speed.py b/tests/test-lz4-speed.py
index 658939c..9d8f4f3 100644
--- a/tests/test-lz4-speed.py
+++ b/tests/test-lz4-speed.py
@@ -204,9 +204,9 @@
     local_branch = branch.split('/')[1]
     version = local_branch.rpartition('-')[2] + '_' + commit
     if not args.dry_run:
-        execute('make -C programs clean lz4 CC=clang MOREFLAGS="-Werror -Wconversion -Wno-sign-conversion -DLZ4_GIT_COMMIT=%s" && ' % version +
+        execute('make clean; CFLAGS="-Werror -Wconversion -Wno-sign-conversion" CPPFLAGS="-DLZ4_GIT_COMMIT=%s" make -C programs lz4 CC=clang && ' % version +
                 'mv programs/lz4 programs/lz4_clang && ' +
-                'make -C programs clean lz4 lz4c32 MOREFLAGS="-DLZ4_GIT_COMMIT=%s"' % version)
+                'make clean && CPPFLAGS="-DLZ4_GIT_COMMIT=%s" make -C programs lz4 lz4c32 ' % version)
     md5_lz4 = hashfile(hashlib.md5(), clone_path + '/programs/lz4')
     md5_lz4c32 = hashfile(hashlib.md5(), clone_path + '/programs/lz4c32')
     md5_lz4_clang = hashfile(hashlib.md5(), clone_path + '/programs/lz4_clang')
diff --git a/tests/test-lz4-testmode.sh b/tests/test-lz4-testmode.sh
new file mode 100755
index 0000000..d37eaad
--- /dev/null
+++ b/tests/test-lz4-testmode.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+
+FPREFIX="tmp-ltm"
+
+set -e
+
+remove () {
+    rm $FPREFIX*
+}
+
+trap remove EXIT
+
+set -x
+
+lz4 -bi0
+datagen > $FPREFIX
+lz4 -f $FPREFIX -c > $FPREFIX.lz4
+lz4 -bdi0 $FPREFIX.lz4 # test benchmark decode-only mode
+lz4 -bdi0 --no-crc $FPREFIX.lz4 # test benchmark decode-only mode
+echo "---- test mode ----"
+datagen | lz4 -t && exit 1
+datagen | lz4 -tf && exit 1
+echo "---- pass-through mode ----"
+echo "Why hello there " > ${FPREFIX}2.lz4
+lz4 -f ${FPREFIX}2.lz4 > $FPREFIX-trash && exit 1
+datagen | lz4 -dc  > $FPREFIX-trash && exit 1
+datagen | lz4 -df > $FPREFIX-trash && exit 1
+datagen | lz4 -dcf > $FPREFIX-trash
+echo "Hello World !" > ${FPREFIX}1
+lz4 -dcf ${FPREFIX}1
+echo "from underground..." > ${FPREFIX}2
+lz4 -dcfm ${FPREFIX}1 ${FPREFIX}2
+echo "---- non-existing source (must fail cleanly) ----"
+lz4     file-does-not-exist && exit 1
+lz4 -f  file-does-not-exist && exit 1
+lz4 -t  file-does-not-exist && exit 1
+lz4 -fm file1-dne file2-dne && exit 1
+true
diff --git a/tests/test-lz4-versions.py b/tests/test-lz4-versions.py
index d7fd199..bd5fdf9 100644
--- a/tests/test-lz4-versions.py
+++ b/tests/test-lz4-versions.py
@@ -7,6 +7,7 @@
 # GPL v2 License
 #
 
+import argparse
 import glob
 import subprocess
 import filecmp
@@ -23,19 +24,45 @@
 test_dat = 'test_dat'
 head = 'v999'
 
-def proc(cmd_args, pipe=True, dummy=False):
-    if dummy:
-        return
-    if pipe:
-        subproc = subprocess.Popen(cmd_args,
-                                   stdout=subprocess.PIPE,
-                                   stderr=subprocess.PIPE)
-    else:
-        subproc = subprocess.Popen(cmd_args)
-    return subproc.communicate()
+parser = argparse.ArgumentParser()
+parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+args = parser.parse_args()
 
-def make(args, pipe=True):
-    return proc([make_cmd] + args, pipe)
+def debug_message(msg):
+    if args.verbose:
+        print(msg)
+
+def env_or_empty(env, key):
+    if key in env:
+        return " " + env[key]
+    return ""
+
+def proc(cmd_args, pipe=True, env=False):
+    if env == False:
+        env = os.environ.copy()
+    debug_message("Executing command {} with env {}".format(cmd_args, env))
+    if pipe:
+        s = subprocess.Popen(cmd_args,
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.PIPE,
+                             env = env)
+    else:
+        s = subprocess.Popen(cmd_args, env = env)
+    stdout_data, stderr_data = s.communicate()
+    if s.poll() != 0:
+        print('Error Code:', s.poll())
+        print('Standard Error:', stderr_data.decode())
+        sys.exit(1)
+    return stdout_data, stderr_data
+
+def make(args, pipe=True, env=False):
+    if env == False:
+        env = os.environ.copy()
+    # favor compilation speed for faster total test time, actual runtime is very short
+    env["CFLAGS"] = env_or_empty(env, 'CFLAGS') + " -O0"
+    # old versions of lz4 may require MOREFLAGS
+    env["MOREFLAGS"] = env_or_empty(env, 'MOREFLAGS') + env_or_empty(env, 'CFLAGS') + env_or_empty(env, 'CPPFLAGS') + env_or_empty(env, 'LDFLAGS')
+    return proc([make_cmd] + args, pipe, env)
 
 def git(args, pipe=True):
     return proc([git_cmd] + args, pipe)
@@ -74,6 +101,7 @@
 
     # Build all release lz4c and lz4c32
     for tag in tags:
+        print("processing tag " + tag)
         os.chdir(base_dir)
         dst_lz4c   = '{}/lz4c.{}'  .format(tmp_dir, tag) # /path/to/lz4/test/lz4test/lz4c.<TAG>
         dst_lz4c32 = '{}/lz4c32.{}'.format(tmp_dir, tag) # /path/to/lz4/test/lz4test/lz4c32.<TAG>
@@ -86,9 +114,11 @@
                 os.chdir(r_dir + '/programs')  # /path/to/lz4/lz4test/<TAG>/programs
             else:
                 os.chdir(programs_dir)
-            make(['clean', 'lz4c'], False)
+            make(['clean'], False)
+            make(['lz4c'], False)
             shutil.copy2('lz4c',   dst_lz4c)
-            make(['clean', 'lz4c32'], False)
+            make(['clean'], False)
+            make(['lz4c32'], False)
             shutil.copy2('lz4c32', dst_lz4c32)
 
     # Compress test.dat by all released lz4c and lz4c32
diff --git a/tests/test-lz4hc-hugefile.sh b/tests/test-lz4hc-hugefile.sh
new file mode 100755
index 0000000..107c313
--- /dev/null
+++ b/tests/test-lz4hc-hugefile.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+set -e
+set -x
+
+datagen -g4200MB | lz4 -v3 | lz4 -qt