Squashed version of #2704. Edit by Rémi Verschelde: Squashed all changes in one commit and fixed some indentation issues. Also applied clang-format to match the new master branch.