Squashed 'third_party/ceres/' changes from e51e9b46f..399cda773

399cda773 Update build documentation to reflect detection of Eigen via config mode
bb127272f Fix typos.
a0ec5c32a Update version history for 2.0.0RC2
3f6d27367 Unify symbol visibility configuration for all compilers
29c2912ee Unbreak the bazel build some more
bf47e1a36 Fix the Bazel build.
600e8c529 fix minor typos
bdcdcc78a update docs for changed cmake usage
3f69e5b36 Corrections from William Rucklidge
8bfdb02fb Rewrite uses of VLOG_IF and LOG_IF.
d1b35ffc1 Corrections from William Rucklidge
f34e80e91 Add dividers between licenses.
65c397dae Fix formatting
f63b1fea9 Add the MIT license text corresponding to the libmv derived files.
542613c13 minor formatting fix for trust_region_minimizer.cc
6d9e9843d Remove inclusion of ceres/eigen.h
eafeca5dc Fix a logging bug in TrustRegionMinimizer.
1fd0be916 Fix default initialisation of IterationCallback::cost
137bbe845 add info about clang-format to contributing docs
d3f66d77f fix formatting generated files (best effort)
a9c7361c8 minor formatting fix (wrongly updated in earlier commit)
7b8f675bf fix formatting for (non-generated) internal source files
921368ce3 Fix a number of typos in covariance.h
7b6b2491c fix formatting for examples
82275d8a4 some fixes for Linux and macOS install docs
9d762d74f fix formatting for public header files
c76478c48 gitignore *.pyc
4e69a475c Fix potential for mismatched release/debug TBB libraries
8e1d8e32a A number of small changes.
368a738e5 AutoDiffCostFunction: optional ownership
8cbd721c1 Add erf and erfc to jet.h, including tests in jet_test.cc
31366cff2 Benchmarks for dynamic autodiff.
29fb08aea Use CMAKE_PREFIX_PATH to pass Homebrew install location
242c703b5 Minor fixes to the documentation
79bbf9510 Add changelog for 2.0.0
41d05f13d Fix lint errors in evaluation_callback_test.cc
4b67903c1 Remove unused variables from problem_test.cc
10449fc36 Add Apache license to the LICENSE file for FixedArray
8c3ecec6d Fix some minor errors in IterationCallback docs
7d3ffcb42 Remove forced CONFIG from find_package(Eigen3)
a029fc0f9 Use latest FindTBB.cmake from VTK project
aa1abbc57 Replace use of GFLAGS_LIBRARIES with export gflags target
db2af1be8 Add Problem::EvaluateResidualBlockAssumingParametersUnchanged
ab4ed32cd Replace NULL with nullptr in the documentation.
ee280e27a Allow SubsetParameterization to accept an empty vector of constant parameters.
4b8c731d8 Fix a bug in DynamicAutoDiffCostFunction
5cb5b35a9 Fixed incorrect argument name in RotationMatrixToQuaternion()
e39d9ed1d Add a missing term and remove a superfluous word
27cab77b6 Reformulate some sentences
8ac6655ce Fix documentation formatting issues
7ef83e075 Update minimum required C++ version for Ceres to C++14
1d75e7568 Improve documentation for LocalParameterization
763398ca4 Update the section on Preconditioners
a614f788a Call EvaluationCallback before evaluating the fixed cost.
70308f7bb Simplify documentation generation.
e886d7e65 Reduce the number of minimizer iterations in evaluation_callback_test.cc
9483e6f2f Simplify DynamicCompressedRowJacobianWriter::Write
323cc55bb Update the version in package.xml to 2.0.0.
303b078b5 Fix few typos and alter a NULL to nullptr.
cca93fed6 Bypass Ceres' FindGlog.cmake in CeresConfig.cmake if possible
77fc1d0fc Use build_depend for private dependencies in Catkin package.xml
a09682f00 Fix MSVC version check to support use of clang-cl front-end
b70687fcc Add namespace qualified Ceres::ceres CMake target
99efa54bd Replace type aliases deprecated/removed in C++17/C++20 from FixedArray
adb973e4a NULL -> nullptr
27b717951 Respect FIND_QUIETLY flag in cmake config file
646959ef1 Do not export class template LineParameterization
1f128d070 Change the type of parameter index/offset to match their getter/setter
072c8f070 Initialize integer variables with integer instead of double
8c36bcc81 Use inline & -inlinehint-threshold in auto-diff benchmarks
57cf20aa5 static const -> static constexpr where we can.
40b27482a Add std::numeric_limit specialization for Jets
e751d6e4f Remove AutodiffCodegen
e9eb76f8e Remove AutodiffCodegen CMake integration
9435e08a7 More clang-tidy and wjr@ comment fixes
d93fac4b7 Remove AutodiffCodegen Tests
2281c6ed2 Fixes for comments from William Rucklidge
d797a87a4 Use Ridders' method in GradientChecker.
41675682d Fix a MSVC type deduction bug in ComputeHouseholderVector
947ec0c1f Remove AutodiffCodegen autodiff benchmarks
27183d661 Allow LocalParameterizations to have zero local size.
7ac7d79dc Remove HelloWorldCodegen example
8c8738bf8 Add photometric and relative-pose residuals to autodiff benchmarks
9f7fb66d6 Add a constant cost function to the autodiff benchmarks
ab0d373e4 Fix a comment in autodiff.h
27bb99714 Change SVD algorithm in covariance computation.
84fdac38e Add const to GetCovarianceMatrix*
6bde61d6b Add line local parameterization.
2c1c0932e Update documentation in autodiff.h
8904fa488 Inline Jet initialization in Autodiff
18a464d4e Remove an errant CR from local_parameterization.cc
5c85f2179 Use ArraySelector in Autodiff
80477ff07 Add class ArraySelector
e7a30359e Pass kNumResiduals to Autodiff
f339d71dd Refactor the automatic differentiation benchmarks.
d37b4cb15 Fix some include headers in codegen/test_utils.cc/h
550766e6d Add Autodiff Brdf Benchmark
8da9876e7 Add more autodiff benchmarks
6da364713 Fix Tukey loss function
cf4185c4e Add Codegen BA Benchmark
75dd30fae Simplify GenerateCodeForFunctor
9049688c6 Default Initialize ExpressionRef to Zero
bf1aff2f0 Fix 3+ nested Jet constructor
92d6541c7 Move Codegen files into codegen/ directory
8e962f37d Add Autodiff Codegen Tests
13c7a22ce Codegen Optimizer API
90799e29e Fix install and unnecessary string copy
032d5844c AutoDiff Code Generation - CMake Integration
d82de91b8 Add ExpressionGraph::Erase(ExpressionId)
c8e35e19f Add namespaces to generated functions and constants
75e575cae Fix use of incomplete type in defaulted Problem methods
8def19616 Remove ExpressionRef Move Constructor
f26f95410 Fix windows MSVC build.
fdf9cfd32 Add functions to find the matching ELSE, ENDIF expressions
678c05b28 Fix invert PSD matrix.
a384a7e96 Remove not used using declaration
a60136b7a Add COMMENT ExpressionType
f212c9295 Let Problem::SetParameterization be called more than once.
a3696835b use CMake function to create CeresConfigVersion
67fcff918 Make Problem movable.
19728e72d Add documentation for Problem::IsParameterBlockConstant
ba6e5fb4a Make the custom uninstall target optional
8547cbd55 Make EventLogger more efficient.
edb8322bd Update the minimum required version of Eigen to 3.3.
aa6ef417f Specify Eigen3_DIR in iOS and Android Travis CI builds
4655f2549 Use find_package() instead of find_dependency() in CeresConfig.cmake
a548766d1 Use glfags target
33dd469a5 Use Eigen3::Eigen target
47e784bb4 NULL-jacobians are handled correctly in generated autodiff code
edd54b83e Update Jet.h and rotation.h to use the new IF/ELSE macros
848c1f90c Update return type in code generator and add tests for logical functions
5010421bb Add the expression return type as a member to Expression
f4dc670ee Improve testing of the codegen system
572ec4a5a Rework Expression creation and insertion
c7337154e Disable the code generation module by default
7fa0f3db4 Explicitly state PUBLIC/PRIVATE when linking
4362a2169 Run clang-format on the public headers. Also update copyright year.
c56702aac Fix installation of codegen headers
0d03e74dc Fix the include in the autodiff codegen example
d16026440 Autodiff Codegen Part 4: Public API
d1703db45 Moved AutoDiffCodeGen macros to a separate (public) header
5ce6c063d Fix ExpressionRef copy constructor and add a move constructor
a90b5a12c Pass ExpressionRef by const reference instead of by value
ea057678c Remove MakeFunctionCall() and add test for Ternary
1084c5460 Quote all configure-expanded paths
3d756b07c Test Expressions with 'insert' instead of a macro
486d81812 Add ExpressionGraph::InsertExpression
3831a1dd3 Expression and ExpressionGraph comparison
9bb1dcb84 Remove definition of ExpressionRef::ExpressionRef(double&);
5be2e4883 Autodiff Codegen Part 3: CodeGenerator
6cd633043 Remove unused ExpressionTypes
7d0d69a4d Fix ExpressionRef
6ba8c57d2 Fix expression_test IsArithmetic
2b494cfb3 Update Travis CI to Bionic & Xcode 11.2
a3dde6877 Require Xcode >= 11.2 on macOS 10.15 (Catalina)
6fd4f072d Autodiff Codegen Part 2: Conditionals
52d6477a4 Detect and disable -fstack-check on macOS 10.15 with Xcode 11
46ca461b7 Fix `gradient_check_relative_precision` docs typo
4247d420f Autodiff Codegen Part 1: Expressions
ba62397d8 Run clang-format on jet.h
667062dcc Introduce BlockSparseMatrixData
17becf461 Remove a CHECK failure from covariance_impl.cc
d7f428e5c Add a missing cast in rotation.h
ea4d66e7e clang-tidy fixes.
be15b842a Integrate the SchurEliminatorForOneFBlock for the case <2,3,6>
087b28f1b Remove use of SetUsage as it creates compilation problems.
573046d7f Protect declarations of lapack functions under CERES_NO_LAPACK
71d638ef3 Add a specialized schur eliminator.
2ffddaccf Use override & final instead of just using virtual.
e4577dd6d Use override instead of virtual for subclasses.
3e5db5bc2 Fixing documentation typo.
82d325b73 Avoid memory allocations in Accelerate Sparse[Refactor/Solve]().
f66b51382 Fix some clang-tidy warnings.
0428e2dd0 Fix missing #include of <memory>
487c1aa51 Expose SubsetPreconditioner in the API
bf709ecac Move EvaluationCallback from Solver::Options to Problem::Options.
059bcb7f8 Drop ROS dependency on catkin
c4dbc927d Default to any other sparse libraries over Accelerate
db1f5b57a Allow some methods in Problem to use const double*.
a60c14525 Explicitly delete the copy constructor and copy assignment operator
084042c25 Lint changes from William Rucklidge
93d869020 Use selfAdjoingView<Upper> in InvertPSDMatrix.
a0cd0854a Speed up InvertPSDMatrix
7b53262b7 Allow Solver::Options::max_num_line_search_step_size_iterations = 0.
3e2cdca54 Make LineSearchMinizer work correctly with negative valued functions.
3ff12a878 Fix a clang-tidy warning in problem_test.cc
57441fe90 Fix two bugs.
1b852c57e Add Problem::EvaluateResidualBlock.
54ba6c27b Fix missing declaration warnings in Ceres code
fac46d50e Modernize ProductParameterization.
53dc6213f Add some missing string-to-enum-to-string convertors.
c0aa9a263 Add checks in rotation.h for inplace operations.
0f57fa82d Update Bazel WORKSPACE for newest Bazel
f8e5fba7b TripletSparseMatrix: guard against self-assignment
939253c20 Fix Eigen alignment issues.
bf67daf79 Add the missing <array> header to fixed_array.h
25e1cdbb6 Switch to FixedArray implementation from abseil.
d467a627b IdentityTransformation -> IdentityParameterization
eaec6a9d0 Fix more typos in CostFunctionToFunctor documentation.
99b5aa4aa Fix typos in CostFunctionToFunctor documentation.
ee7e2cb3c Set Homebrew paths via HINTS not CMAKE_PREFIX_PATH
4f8a01853 Revert "Fix custom Eigen on macos (EIGEN_INCLUDE_DIR_HINTS)"
e6c5c7226 Fix custom Eigen on macos (EIGEN_INCLUDE_DIR_HINTS)
5a56d522e Add the 3,3,3 template specialization.
df5c23116 Reorder initializer list to make -Wreorder happy
0fcfdb0b4 Fix the build breakage caused by the last commit.
9b9e9f0dc Reduce machoness of macro definition in cost_functor_to_function_test.cc
21d40daa0 Remove UTF-8 chars
9350e57a4 Enable optional use of sanitizers
0456edffb Update Travis CI Linux distro to 16.04 (Xenial)
bef0dfe35 Fix a typo in cubic_interpolation.h
056ba9bb1 Add AutoDiffFirstOrderFunction
6e527392d Update googletest/googlemock to db9b85e2.
1b2940749 Clarify documentation of BiCubicInterpolator::Evaluate for out-of-bounds values

Change-Id: Id61dd832e8fbe286deb0799aa1399d4017031dae
git-subtree-dir: third_party/ceres
git-subtree-split: 399cda773035d99eaf1f4a129a666b3c4df9d1b1
diff --git a/examples/BUILD b/examples/BUILD
index 4d8f1bb..90daf21 100644
--- a/examples/BUILD
+++ b/examples/BUILD
@@ -35,7 +35,7 @@
 
 EXAMPLE_DEPS = [
     "//:ceres",
-    "@com_github_eigen_eigen//:eigen",
+    "@com_gitlab_libeigen_eigen//:eigen",
     "@com_github_gflags_gflags//:gflags",
 ]
 
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 3d86be8..7f9b117 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -36,25 +36,23 @@
 endif()
 
 add_executable(helloworld helloworld.cc)
-target_link_libraries(helloworld ceres)
+target_link_libraries(helloworld Ceres::ceres)
 
 add_executable(helloworld_numeric_diff helloworld_numeric_diff.cc)
-target_link_libraries(helloworld_numeric_diff ceres)
+target_link_libraries(helloworld_numeric_diff Ceres::ceres)
 
 add_executable(helloworld_analytic_diff helloworld_analytic_diff.cc)
-target_link_libraries(helloworld_analytic_diff ceres)
+target_link_libraries(helloworld_analytic_diff Ceres::ceres)
 
 add_executable(curve_fitting curve_fitting.cc)
-target_link_libraries(curve_fitting ceres)
+target_link_libraries(curve_fitting Ceres::ceres)
 
 add_executable(rosenbrock rosenbrock.cc)
-target_link_libraries(rosenbrock ceres)
+target_link_libraries(rosenbrock Ceres::ceres)
 
 add_executable(curve_fitting_c curve_fitting.c)
-target_link_libraries(curve_fitting_c ceres)
-# Force CMake to link curve_fitting_c using the C linker, this is important
-# when Ceres was compiled using C++11 to ensure that -std=c++11 is not passed
-# through.
+target_link_libraries(curve_fitting_c Ceres::ceres)
+# Force CMake to link curve_fitting_c using the C linker.
 set_target_properties(curve_fitting_c PROPERTIES LINKER_LANGUAGE C)
 # As this is a C file #including <math.h> we have to explicitly add the math
 # library (libm). Although some compilers (dependent upon options) will accept
@@ -64,51 +62,51 @@
 endif (NOT MSVC)
 
 add_executable(ellipse_approximation ellipse_approximation.cc)
-target_link_libraries(ellipse_approximation ceres)
+target_link_libraries(ellipse_approximation Ceres::ceres)
 
 add_executable(robust_curve_fitting robust_curve_fitting.cc)
-target_link_libraries(robust_curve_fitting ceres)
+target_link_libraries(robust_curve_fitting Ceres::ceres)
 
 add_executable(simple_bundle_adjuster simple_bundle_adjuster.cc)
-target_link_libraries(simple_bundle_adjuster ceres)
+target_link_libraries(simple_bundle_adjuster Ceres::ceres)
 
 if (GFLAGS)
   add_executable(powell powell.cc)
-  target_link_libraries(powell ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(powell Ceres::ceres gflags)
 
   add_executable(nist nist.cc)
-  target_link_libraries(nist ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(nist Ceres::ceres gflags)
   if (MSVC)
     target_compile_options(nist PRIVATE "/bigobj")
   endif()
 
   add_executable(more_garbow_hillstrom more_garbow_hillstrom.cc)
-  target_link_libraries(more_garbow_hillstrom ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(more_garbow_hillstrom Ceres::ceres gflags)
 
   add_executable(circle_fit circle_fit.cc)
-  target_link_libraries(circle_fit ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(circle_fit Ceres::ceres gflags)
 
   add_executable(bundle_adjuster
                  bundle_adjuster.cc
                  bal_problem.cc)
-  target_link_libraries(bundle_adjuster ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(bundle_adjuster Ceres::ceres gflags)
 
   add_executable(libmv_bundle_adjuster
                  libmv_bundle_adjuster.cc)
-  target_link_libraries(libmv_bundle_adjuster ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(libmv_bundle_adjuster Ceres::ceres gflags)
 
   add_executable(libmv_homography
                  libmv_homography.cc)
-  target_link_libraries(libmv_homography ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(libmv_homography Ceres::ceres gflags)
 
   add_executable(denoising
                  denoising.cc
                  fields_of_experts.cc)
-  target_link_libraries(denoising ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(denoising Ceres::ceres gflags)
 
   add_executable(robot_pose_mle
                  robot_pose_mle.cc)
-  target_link_libraries(robot_pose_mle ceres ${GFLAGS_LIBRARIES})
+  target_link_libraries(robot_pose_mle Ceres::ceres gflags)
 
 endif (GFLAGS)
 
diff --git a/examples/bal_problem.cc b/examples/bal_problem.cc
index 1ee3c81..ceac89a 100644
--- a/examples/bal_problem.cc
+++ b/examples/bal_problem.cc
@@ -35,6 +35,7 @@
 #include <fstream>
 #include <string>
 #include <vector>
+
 #include "Eigen/Core"
 #include "ceres/rotation.h"
 #include "glog/logging.h"
@@ -46,7 +47,7 @@
 typedef Eigen::Map<Eigen::VectorXd> VectorRef;
 typedef Eigen::Map<const Eigen::VectorXd> ConstVectorRef;
 
-template<typename T>
+template <typename T>
 void FscanfOrDie(FILE* fptr, const char* format, T* value) {
   int num_scanned = fscanf(fptr, format, value);
   if (num_scanned != 1) {
@@ -82,9 +83,8 @@
   FscanfOrDie(fptr, "%d", &num_points_);
   FscanfOrDie(fptr, "%d", &num_observations_);
 
-  VLOG(1) << "Header: " << num_cameras_
-          << " " << num_points_
-          << " " << num_observations_;
+  VLOG(1) << "Header: " << num_cameras_ << " " << num_points_ << " "
+          << num_observations_;
 
   point_index_ = new int[num_observations_];
   camera_index_ = new int[num_observations_];
@@ -97,7 +97,7 @@
     FscanfOrDie(fptr, "%d", camera_index_ + i);
     FscanfOrDie(fptr, "%d", point_index_ + i);
     for (int j = 0; j < 2; ++j) {
-      FscanfOrDie(fptr, "%lf", observations_ + 2*i + j);
+      FscanfOrDie(fptr, "%lf", observations_ + 2 * i + j);
     }
   }
 
@@ -119,7 +119,7 @@
       quaternion_cursor += 4;
       original_cursor += 3;
       for (int j = 4; j < 10; ++j) {
-       *quaternion_cursor++ = *original_cursor++;
+        *quaternion_cursor++ = *original_cursor++;
       }
     }
     // Copy the rest of the points.
@@ -127,7 +127,7 @@
       *quaternion_cursor++ = *original_cursor++;
     }
     // Swap in the quaternion parameters.
-    delete []parameters_;
+    delete[] parameters_;
     parameters_ = quaternion_parameters;
   }
 }
@@ -181,25 +181,25 @@
 void BALProblem::WriteToPLYFile(const std::string& filename) const {
   std::ofstream of(filename.c_str());
 
-  of << "ply"
-     << '\n' << "format ascii 1.0"
-     << '\n' << "element vertex " << num_cameras_ + num_points_
-     << '\n' << "property float x"
-     << '\n' << "property float y"
-     << '\n' << "property float z"
-     << '\n' << "property uchar red"
-     << '\n' << "property uchar green"
-     << '\n' << "property uchar blue"
-     << '\n' << "end_header" << std::endl;
+  of << "ply" << '\n'
+     << "format ascii 1.0" << '\n'
+     << "element vertex " << num_cameras_ + num_points_ << '\n'
+     << "property float x" << '\n'
+     << "property float y" << '\n'
+     << "property float z" << '\n'
+     << "property uchar red" << '\n'
+     << "property uchar green" << '\n'
+     << "property uchar blue" << '\n'
+     << "end_header" << std::endl;
 
   // Export extrinsic data (i.e. camera centers) as green points.
   double angle_axis[3];
   double center[3];
-  for (int i = 0; i < num_cameras(); ++i)  {
+  for (int i = 0; i < num_cameras(); ++i) {
     const double* camera = cameras() + camera_block_size() * i;
     CameraToAngleAxisAndCenter(camera, angle_axis, center);
-    of << center[0] << ' ' << center[1] << ' ' << center[2]
-       << " 0 255 0" << '\n';
+    of << center[0] << ' ' << center[1] << ' ' << center[2] << " 0 255 0"
+       << '\n';
   }
 
   // Export the structure (i.e. 3D Points) as white points.
@@ -226,9 +226,8 @@
 
   // c = -R't
   Eigen::VectorXd inverse_rotation = -angle_axis_ref;
-  AngleAxisRotatePoint(inverse_rotation.data(),
-                       camera + camera_block_size() - 6,
-                       center);
+  AngleAxisRotatePoint(
+      inverse_rotation.data(), camera + camera_block_size() - 6, center);
   VectorRef(center, 3) *= -1.0;
 }
 
@@ -243,13 +242,10 @@
   }
 
   // t = -R * c
-  AngleAxisRotatePoint(angle_axis,
-                       center,
-                       camera + camera_block_size() - 6);
+  AngleAxisRotatePoint(angle_axis, center, camera + camera_block_size() - 6);
   VectorRef(camera + camera_block_size() - 6, 3) *= -1.0;
 }
 
-
 void BALProblem::Normalize() {
   // Compute the marginal median of the geometry.
   std::vector<double> tmp(num_points_);
@@ -329,10 +325,10 @@
 }
 
 BALProblem::~BALProblem() {
-  delete []point_index_;
-  delete []camera_index_;
-  delete []observations_;
-  delete []parameters_;
+  delete[] point_index_;
+  delete[] camera_index_;
+  delete[] observations_;
+  delete[] parameters_;
 }
 
 }  // namespace examples
diff --git a/examples/bal_problem.h b/examples/bal_problem.h
index e9a348e..e6d4ace 100644
--- a/examples/bal_problem.h
+++ b/examples/bal_problem.h
@@ -65,6 +65,7 @@
                const double translation_sigma,
                const double point_sigma);
 
+  // clang-format off
   int camera_block_size()      const { return use_quaternions_ ? 10 : 9; }
   int point_block_size()       const { return 3;                         }
   int num_cameras()            const { return num_cameras_;              }
@@ -77,8 +78,9 @@
   const double* parameters()   const { return parameters_;               }
   const double* cameras()      const { return parameters_;               }
   double* mutable_cameras()          { return parameters_;               }
+  // clang-format on
   double* mutable_points() {
-    return parameters_  + camera_block_size() * num_cameras_;
+    return parameters_ + camera_block_size() * num_cameras_;
   }
 
  private:
diff --git a/examples/bundle_adjuster.cc b/examples/bundle_adjuster.cc
index 5619c52..e7b154e 100644
--- a/examples/bundle_adjuster.cc
+++ b/examples/bundle_adjuster.cc
@@ -64,6 +64,9 @@
 #include "glog/logging.h"
 #include "snavely_reprojection_error.h"
 
+// clang-format makes the gflags definitions too verbose
+// clang-format off
+
 DEFINE_string(input, "", "Input File name");
 DEFINE_string(trust_region_strategy, "levenberg_marquardt",
               "Options are: levenberg_marquardt, dogleg.");
@@ -74,7 +77,7 @@
             "refine each successful trust region step.");
 
 DEFINE_string(blocks_for_inner_iterations, "automatic", "Options are: "
-            "automatic, cameras, points, cameras,points, points,cameras");
+              "automatic, cameras, points, cameras,points, points,cameras");
 
 DEFINE_string(linear_solver, "sparse_schur", "Options are: "
               "sparse_schur, dense_schur, iterative_schur, sparse_normal_cholesky, "
@@ -100,8 +103,8 @@
 DEFINE_bool(robustify, false, "Use a robust loss function.");
 
 DEFINE_double(eta, 1e-2, "Default value for eta. Eta determines the "
-             "accuracy of each linear solve of the truncated newton step. "
-             "Changing this parameter can affect solve performance.");
+              "accuracy of each linear solve of the truncated newton step. "
+              "Changing this parameter can affect solve performance.");
 
 DEFINE_int32(num_threads, 1, "Number of threads.");
 DEFINE_int32(num_iterations, 5, "Number of iterations.");
@@ -126,8 +129,11 @@
 DEFINE_string(final_ply, "", "Export the refined BAL file data as a PLY "
               "file.");
 
+// clang-format on
+
 namespace ceres {
 namespace examples {
+namespace {
 
 void SetLinearSolver(Solver::Options* options) {
   CHECK(StringToLinearSolverType(FLAGS_linear_solver,
@@ -137,11 +143,11 @@
   CHECK(StringToVisibilityClusteringType(FLAGS_visibility_clustering,
                                          &options->visibility_clustering_type));
   CHECK(StringToSparseLinearAlgebraLibraryType(
-            FLAGS_sparse_linear_algebra_library,
-            &options->sparse_linear_algebra_library_type));
+      FLAGS_sparse_linear_algebra_library,
+      &options->sparse_linear_algebra_library_type));
   CHECK(StringToDenseLinearAlgebraLibraryType(
-            FLAGS_dense_linear_algebra_library,
-            &options->dense_linear_algebra_library_type));
+      FLAGS_dense_linear_algebra_library,
+      &options->dense_linear_algebra_library_type));
   options->use_explicit_schur_complement = FLAGS_explicit_schur_complement;
   options->use_mixed_precision_solves = FLAGS_mixed_precision_solves;
   options->max_num_refinement_iterations = FLAGS_max_num_refinement_iterations;
@@ -161,31 +167,37 @@
       LOG(INFO) << "Camera blocks for inner iterations";
       options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
       for (int i = 0; i < num_cameras; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0);
+        options->inner_iteration_ordering->AddElementToGroup(
+            cameras + camera_block_size * i, 0);
       }
     } else if (FLAGS_blocks_for_inner_iterations == "points") {
       LOG(INFO) << "Point blocks for inner iterations";
       options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
       for (int i = 0; i < num_points; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0);
+        options->inner_iteration_ordering->AddElementToGroup(
+            points + point_block_size * i, 0);
       }
     } else if (FLAGS_blocks_for_inner_iterations == "cameras,points") {
       LOG(INFO) << "Camera followed by point blocks for inner iterations";
       options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
       for (int i = 0; i < num_cameras; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0);
+        options->inner_iteration_ordering->AddElementToGroup(
+            cameras + camera_block_size * i, 0);
       }
       for (int i = 0; i < num_points; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 1);
+        options->inner_iteration_ordering->AddElementToGroup(
+            points + point_block_size * i, 1);
       }
     } else if (FLAGS_blocks_for_inner_iterations == "points,cameras") {
       LOG(INFO) << "Point followed by camera blocks for inner iterations";
       options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
       for (int i = 0; i < num_cameras; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 1);
+        options->inner_iteration_ordering->AddElementToGroup(
+            cameras + camera_block_size * i, 1);
       }
       for (int i = 0; i < num_points; ++i) {
-        options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0);
+        options->inner_iteration_ordering->AddElementToGroup(
+            points + point_block_size * i, 0);
       }
     } else if (FLAGS_blocks_for_inner_iterations == "automatic") {
       LOG(INFO) << "Choosing automatic blocks for inner iterations";
@@ -210,8 +222,7 @@
     return;
   }
 
-  ceres::ParameterBlockOrdering* ordering =
-      new ceres::ParameterBlockOrdering;
+  ceres::ParameterBlockOrdering* ordering = new ceres::ParameterBlockOrdering;
 
   // The points come before the cameras.
   for (int i = 0; i < num_points; ++i) {
@@ -265,14 +276,11 @@
     CostFunction* cost_function;
     // Each Residual block takes a point and a camera as input and
     // outputs a 2 dimensional residual.
-    cost_function =
-        (FLAGS_use_quaternions)
-        ? SnavelyReprojectionErrorWithQuaternions::Create(
-            observations[2 * i + 0],
-            observations[2 * i + 1])
-        : SnavelyReprojectionError::Create(
-            observations[2 * i + 0],
-            observations[2 * i + 1]);
+    cost_function = (FLAGS_use_quaternions)
+                        ? SnavelyReprojectionErrorWithQuaternions::Create(
+                              observations[2 * i + 0], observations[2 * i + 1])
+                        : SnavelyReprojectionError::Create(
+                              observations[2 * i + 0], observations[2 * i + 1]);
 
     // If enabled use Huber's loss function.
     LossFunction* loss_function = FLAGS_robustify ? new HuberLoss(1.0) : NULL;
@@ -288,9 +296,8 @@
 
   if (FLAGS_use_quaternions && FLAGS_use_local_parameterization) {
     LocalParameterization* camera_parameterization =
-        new ProductParameterization(
-            new QuaternionParameterization(),
-            new IdentityParameterization(6));
+        new ProductParameterization(new QuaternionParameterization(),
+                                    new IdentityParameterization(6));
     for (int i = 0; i < bal_problem->num_cameras(); ++i) {
       problem->SetParameterization(cameras + camera_block_size * i,
                                    camera_parameterization);
@@ -309,9 +316,8 @@
 
   srand(FLAGS_random_seed);
   bal_problem.Normalize();
-  bal_problem.Perturb(FLAGS_rotation_sigma,
-                      FLAGS_translation_sigma,
-                      FLAGS_point_sigma);
+  bal_problem.Perturb(
+      FLAGS_rotation_sigma, FLAGS_translation_sigma, FLAGS_point_sigma);
 
   BuildProblem(&bal_problem, &problem);
   Solver::Options options;
@@ -327,11 +333,12 @@
   }
 }
 
+}  // namespace
 }  // namespace examples
 }  // namespace ceres
 
 int main(int argc, char** argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
   if (FLAGS_input.empty()) {
     LOG(ERROR) << "Usage: bundle_adjuster --input=bal_problem";
diff --git a/examples/circle_fit.cc b/examples/circle_fit.cc
index b58ce4e..c542475 100644
--- a/examples/circle_fit.cc
+++ b/examples/circle_fit.cc
@@ -48,7 +48,7 @@
 // consider instead of using this one. If you already have a decent guess, Ceres
 // can squeeze down the last bit of error.
 //
-//   [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m
+//   [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m  // NOLINT
 
 #include <cstdio>
 #include <vector>
@@ -65,8 +65,10 @@
 using ceres::Solve;
 using ceres::Solver;
 
-DEFINE_double(robust_threshold, 0.0, "Robust loss parameter. Set to 0 for "
-              "normal squared error (no robustification).");
+DEFINE_double(robust_threshold,
+              0.0,
+              "Robust loss parameter. Set to 0 for normal squared error (no "
+              "robustification).");
 
 // The cost for a single sample. The returned residual is related to the
 // distance of the point from the circle (passed in as x, y, m parameters).
@@ -76,10 +78,11 @@
 class DistanceFromCircleCost {
  public:
   DistanceFromCircleCost(double xx, double yy) : xx_(xx), yy_(yy) {}
-  template <typename T> bool operator()(const T* const x,
-                                        const T* const y,
-                                        const T* const m,  // r = m^2
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x,
+                  const T* const y,
+                  const T* const m,  // r = m^2
+                  T* residual) const {
     // Since the radius is parameterized as m^2, unpack m to get r.
     T r = *m * *m;
 
@@ -97,7 +100,7 @@
     // distance in the metric sense (it has units distance^2) it produces more
     // robust fits when there are outliers. This is because the cost surface is
     // more convex.
-    residual[0] = r*r - xp*xp - yp*yp;
+    residual[0] = r * r - xp * xp - yp * yp;
     return true;
   }
 
@@ -107,7 +110,7 @@
 };
 
 int main(int argc, char** argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
 
   double x, y, r;
@@ -137,7 +140,7 @@
   double xx, yy;
   int num_points = 0;
   while (scanf("%lf %lf\n", &xx, &yy) == 2) {
-    CostFunction *cost =
+    CostFunction* cost =
         new AutoDiffCostFunction<DistanceFromCircleCost, 1, 1, 1, 1>(
             new DistanceFromCircleCost(xx, yy));
     problem.AddResidualBlock(cost, loss, &x, &y, &m);
diff --git a/examples/curve_fitting.c b/examples/curve_fitting.c
index 0027aa8..fef5581 100644
--- a/examples/curve_fitting.c
+++ b/examples/curve_fitting.c
@@ -123,10 +123,10 @@
 /* This is the equivalent of a use-defined CostFunction in the C++ Ceres API.
  * This is passed as a callback to the Ceres C API, which internally converts
  * the callback into a CostFunction. */
-int exponential_residual(void* user_data,
-                         double** parameters,
-                         double* residuals,
-                         double** jacobians) {
+static int exponential_residual(void* user_data,
+                                double** parameters,
+                                double* residuals,
+                                double** jacobians) {
   double* measurement = (double*) user_data;
   double x = measurement[0];
   double y = measurement[1];
diff --git a/examples/curve_fitting.cc b/examples/curve_fitting.cc
index 3f577f8..fc7ff94 100644
--- a/examples/curve_fitting.cc
+++ b/examples/curve_fitting.cc
@@ -34,8 +34,8 @@
 using ceres::AutoDiffCostFunction;
 using ceres::CostFunction;
 using ceres::Problem;
-using ceres::Solver;
 using ceres::Solve;
+using ceres::Solver;
 
 // Data generated using the following octave code.
 //   randn('seed', 23497);
@@ -48,6 +48,7 @@
 //   data = [x', y_observed'];
 
 const int kNumObservations = 67;
+// clang-format off
 const double data[] = {
   0.000000e+00, 1.133898e+00,
   7.500000e-02, 1.334902e+00,
@@ -117,14 +118,13 @@
   4.875000e+00, 4.727863e+00,
   4.950000e+00, 4.669206e+00,
 };
+// clang-format on
 
 struct ExponentialResidual {
-  ExponentialResidual(double x, double y)
-      : x_(x), y_(y) {}
+  ExponentialResidual(double x, double y) : x_(x), y_(y) {}
 
-  template <typename T> bool operator()(const T* const m,
-                                        const T* const c,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const m, const T* const c, T* residual) const {
     residual[0] = y_ - exp(m[0] * x_ + c[0]);
     return true;
   }
@@ -146,7 +146,8 @@
         new AutoDiffCostFunction<ExponentialResidual, 1, 1, 1>(
             new ExponentialResidual(data[2 * i], data[2 * i + 1])),
         NULL,
-        &m, &c);
+        &m,
+        &c);
   }
 
   Solver::Options options;
diff --git a/examples/denoising.cc b/examples/denoising.cc
index a8bdd7c..61ea2c6 100644
--- a/examples/denoising.cc
+++ b/examples/denoising.cc
@@ -41,27 +41,70 @@
 #include <algorithm>
 #include <cmath>
 #include <iostream>
-#include <vector>
+#include <random>
 #include <sstream>
 #include <string>
+#include <vector>
 
 #include "ceres/ceres.h"
+#include "fields_of_experts.h"
 #include "gflags/gflags.h"
 #include "glog/logging.h"
-
-#include "fields_of_experts.h"
 #include "pgm_image.h"
 
 DEFINE_string(input, "", "File to which the output image should be written");
 DEFINE_string(foe_file, "", "FoE file to use");
 DEFINE_string(output, "", "File to which the output image should be written");
 DEFINE_double(sigma, 20.0, "Standard deviation of noise");
-DEFINE_bool(verbose, false, "Prints information about the solver progress.");
-DEFINE_bool(line_search, false, "Use a line search instead of trust region "
+DEFINE_string(trust_region_strategy,
+              "levenberg_marquardt",
+              "Options are: levenberg_marquardt, dogleg.");
+DEFINE_string(dogleg,
+              "traditional_dogleg",
+              "Options are: traditional_dogleg,"
+              "subspace_dogleg.");
+DEFINE_string(linear_solver,
+              "sparse_normal_cholesky",
+              "Options are: "
+              "sparse_normal_cholesky and cgnr.");
+DEFINE_string(preconditioner,
+              "jacobi",
+              "Options are: "
+              "identity, jacobi, subset");
+DEFINE_string(sparse_linear_algebra_library,
+              "suite_sparse",
+              "Options are: suite_sparse, cx_sparse and eigen_sparse");
+DEFINE_double(eta,
+              1e-2,
+              "Default value for eta. Eta determines the "
+              "accuracy of each linear solve of the truncated newton step. "
+              "Changing this parameter can affect solve performance.");
+DEFINE_int32(num_threads, 1, "Number of threads.");
+DEFINE_int32(num_iterations, 10, "Number of iterations.");
+DEFINE_bool(nonmonotonic_steps,
+            false,
+            "Trust region algorithm can use"
+            " nonmonotic steps.");
+DEFINE_bool(inner_iterations,
+            false,
+            "Use inner iterations to non-linearly "
+            "refine each successful trust region step.");
+DEFINE_bool(mixed_precision_solves, false, "Use mixed precision solves.");
+DEFINE_int32(max_num_refinement_iterations,
+             0,
+             "Iterative refinement iterations");
+DEFINE_bool(line_search,
+            false,
+            "Use a line search instead of trust region "
             "algorithm.");
+DEFINE_double(subset_fraction,
+              0.2,
+              "The fraction of residual blocks to use for the"
+              " subset preconditioner.");
 
 namespace ceres {
 namespace examples {
+namespace {
 
 // This cost function is used to build the data term.
 //
@@ -69,8 +112,7 @@
 //
 class QuadraticCostFunction : public ceres::SizedCostFunction<1, 1> {
  public:
-  QuadraticCostFunction(double a, double b)
-    : sqrta_(std::sqrt(a)), b_(b) {}
+  QuadraticCostFunction(double a, double b) : sqrta_(std::sqrt(a)), b_(b) {}
   virtual bool Evaluate(double const* const* parameters,
                         double* residuals,
                         double** jacobians) const {
@@ -81,6 +123,7 @@
     }
     return true;
   }
+
  private:
   double sqrta_, b_;
 };
@@ -93,13 +136,11 @@
   // Create the data term
   CHECK_GT(FLAGS_sigma, 0.0);
   const double coefficient = 1 / (2.0 * FLAGS_sigma * FLAGS_sigma);
-  for (unsigned index = 0; index < image.NumPixels(); ++index) {
-    ceres::CostFunction* cost_function =
-        new QuadraticCostFunction(coefficient,
-                                  image.PixelFromLinearIndex(index));
-    problem->AddResidualBlock(cost_function,
-                              NULL,
-                              solution->MutablePixelFromLinearIndex(index));
+  for (int index = 0; index < image.NumPixels(); ++index) {
+    ceres::CostFunction* cost_function = new QuadraticCostFunction(
+        coefficient, image.PixelFromLinearIndex(index));
+    problem->AddResidualBlock(
+        cost_function, NULL, solution->MutablePixelFromLinearIndex(index));
   }
 
   // Create Ceres cost and loss functions for regularization. One is needed for
@@ -126,14 +167,41 @@
       // For this patch with coordinates (x, y), we will add foe.NumFilters()
       // terms to the objective function.
       for (int alpha_index = 0; alpha_index < foe.NumFilters(); ++alpha_index) {
-        problem->AddResidualBlock(cost_function[alpha_index],
-                                  loss_function[alpha_index],
-                                  pixels);
+        problem->AddResidualBlock(
+            cost_function[alpha_index], loss_function[alpha_index], pixels);
       }
     }
   }
 }
 
+void SetLinearSolver(Solver::Options* options) {
+  CHECK(StringToLinearSolverType(FLAGS_linear_solver,
+                                 &options->linear_solver_type));
+  CHECK(StringToPreconditionerType(FLAGS_preconditioner,
+                                   &options->preconditioner_type));
+  CHECK(StringToSparseLinearAlgebraLibraryType(
+      FLAGS_sparse_linear_algebra_library,
+      &options->sparse_linear_algebra_library_type));
+  options->use_mixed_precision_solves = FLAGS_mixed_precision_solves;
+  options->max_num_refinement_iterations = FLAGS_max_num_refinement_iterations;
+}
+
+void SetMinimizerOptions(Solver::Options* options) {
+  options->max_num_iterations = FLAGS_num_iterations;
+  options->minimizer_progress_to_stdout = true;
+  options->num_threads = FLAGS_num_threads;
+  options->eta = FLAGS_eta;
+  options->use_nonmonotonic_steps = FLAGS_nonmonotonic_steps;
+  if (FLAGS_line_search) {
+    options->minimizer_type = ceres::LINE_SEARCH;
+  }
+
+  CHECK(StringToTrustRegionStrategyType(FLAGS_trust_region_strategy,
+                                        &options->trust_region_strategy_type));
+  CHECK(StringToDoglegType(FLAGS_dogleg, &options->dogleg_type));
+  options->use_inner_iterations = FLAGS_inner_iterations;
+}
+
 // Solves the FoE problem using Ceres and post-processes it to make sure the
 // solution stays within [0, 255].
 void SolveProblem(Problem* problem, PGMImage<double>* solution) {
@@ -141,23 +209,33 @@
   // to be faster for 2x2 filters, but gives solutions with slightly higher
   // objective function value.
   ceres::Solver::Options options;
-  options.max_num_iterations = 100;
-  if (FLAGS_verbose) {
-    options.minimizer_progress_to_stdout = true;
-  }
-
-  if (FLAGS_line_search) {
-    options.minimizer_type = ceres::LINE_SEARCH;
-  }
-
-  options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
+  SetMinimizerOptions(&options);
+  SetLinearSolver(&options);
   options.function_tolerance = 1e-3;  // Enough for denoising.
 
+  if (options.linear_solver_type == ceres::CGNR &&
+      options.preconditioner_type == ceres::SUBSET) {
+    std::vector<ResidualBlockId> residual_blocks;
+    problem->GetResidualBlocks(&residual_blocks);
+
+    // To use the SUBSET preconditioner we need to provide a list of
+    // residual blocks (rows of the Jacobian). The denoising problem
+    // has fairly general sparsity, and there is no apriori reason to
+    // select one residual block over another, so we will randomly
+    // subsample the residual blocks with probability subset_fraction.
+    std::default_random_engine engine;
+    std::uniform_real_distribution<> distribution(0, 1);  // rage 0 - 1
+    for (auto residual_block : residual_blocks) {
+      if (distribution(engine) <= FLAGS_subset_fraction) {
+        options.residual_blocks_for_subset_preconditioner.insert(
+            residual_block);
+      }
+    }
+  }
+
   ceres::Solver::Summary summary;
   ceres::Solve(options, problem, &summary);
-  if (FLAGS_verbose) {
-    std::cout << summary.FullReport() << "\n";
-  }
+  std::cout << summary.FullReport() << "\n";
 
   // Make the solution stay in [0, 255].
   for (int x = 0; x < solution->width(); ++x) {
@@ -167,26 +245,24 @@
     }
   }
 }
+
+}  // namespace
 }  // namespace examples
 }  // namespace ceres
 
 int main(int argc, char** argv) {
   using namespace ceres::examples;
-  std::string
-      usage("This program denoises an image using Ceres.  Sample usage:\n");
-  usage += argv[0];
-  usage += " --input=<noisy image PGM file> --foe_file=<FoE file name>";
-  CERES_GFLAGS_NAMESPACE::SetUsageMessage(usage);
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
 
   if (FLAGS_input.empty()) {
-    std::cerr << "Please provide an image file name.\n";
+    std::cerr << "Please provide an image file name using -input.\n";
     return 1;
   }
 
   if (FLAGS_foe_file.empty()) {
-    std::cerr << "Please provide a Fields of Experts file name.\n";
+    std::cerr << "Please provide a Fields of Experts file name using -foe_file."
+                 "\n";
     return 1;
   }
 
diff --git a/examples/ellipse_approximation.cc b/examples/ellipse_approximation.cc
index f519f0c..74782f4 100644
--- a/examples/ellipse_approximation.cc
+++ b/examples/ellipse_approximation.cc
@@ -37,6 +37,7 @@
 
 #include <cmath>
 #include <vector>
+
 #include "ceres/ceres.h"
 #include "glog/logging.h"
 
@@ -53,6 +54,7 @@
 
 const int kYRows = 212;
 const int kYCols = 2;
+// clang-format off
 const double kYData[kYRows * kYCols] = {
   +3.871364e+00, +9.916027e-01,
   +3.864003e+00, +1.034148e+00,
@@ -267,6 +269,7 @@
   +3.870542e+00, +9.996121e-01,
   +3.865424e+00, +1.028474e+00
 };
+// clang-format on
 ceres::ConstMatrixRef kY(kYData, kYRows, kYCols);
 
 class PointToLineSegmentContourCostFunction : public ceres::CostFunction {
@@ -357,9 +360,9 @@
   const double sqrt_weight_;
 };
 
-bool SolveWithFullReport(ceres::Solver::Options options,
-                         ceres::Problem* problem,
-                         bool dynamic_sparsity) {
+static bool SolveWithFullReport(ceres::Solver::Options options,
+                                ceres::Problem* problem,
+                                bool dynamic_sparsity) {
   options.dynamic_sparsity = dynamic_sparsity;
 
   ceres::Solver::Summary summary;
@@ -382,9 +385,8 @@
 
   // Eigen::MatrixXd is column major so we define our own MatrixXd which is
   // row major. Eigen::VectorXd can be used directly.
-  typedef Eigen::Matrix<double,
-                        Eigen::Dynamic, Eigen::Dynamic,
-                        Eigen::RowMajor> MatrixXd;
+  typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
+      MatrixXd;
   using Eigen::VectorXd;
 
   // `X` is the matrix of control points which make up the contour of line
@@ -420,18 +422,18 @@
   for (int i = 0; i < num_observations; ++i) {
     parameter_blocks[0] = &t[i];
     problem.AddResidualBlock(
-      PointToLineSegmentContourCostFunction::Create(num_segments, kY.row(i)),
-      NULL,
-      parameter_blocks);
+        PointToLineSegmentContourCostFunction::Create(num_segments, kY.row(i)),
+        NULL,
+        parameter_blocks);
   }
 
   // Add regularization to minimize the length of the line segment contour.
   for (int i = 0; i < num_segments; ++i) {
     problem.AddResidualBlock(
-      EuclideanDistanceFunctor::Create(sqrt(regularization_weight)),
-      NULL,
-      X.data() + 2 * i,
-      X.data() + 2 * ((i + 1) % num_segments));
+        EuclideanDistanceFunctor::Create(sqrt(regularization_weight)),
+        NULL,
+        X.data() + 2 * i,
+        X.data() + 2 * ((i + 1) % num_segments));
   }
 
   ceres::Solver::Options options;
diff --git a/examples/fields_of_experts.cc b/examples/fields_of_experts.cc
index 60d179a..7b7983e 100644
--- a/examples/fields_of_experts.cc
+++ b/examples/fields_of_experts.cc
@@ -33,8 +33,8 @@
 
 #include "fields_of_experts.h"
 
-#include <fstream>
 #include <cmath>
+#include <fstream>
 
 #include "pgm_image.h"
 
@@ -80,14 +80,12 @@
   const double sum = 1.0 + sq_norm * c;
   const double inv = 1.0 / sum;
   // 'sum' and 'inv' are always positive, assuming that 's' is.
-  rho[0] = alpha_ *  log(sum);
+  rho[0] = alpha_ * log(sum);
   rho[1] = alpha_ * c * inv;
-  rho[2] = - alpha_ * c * c * inv * inv;
+  rho[2] = -alpha_ * c * c * inv * inv;
 }
 
-FieldsOfExperts::FieldsOfExperts()
-    :  size_(0), num_filters_(0) {
-}
+FieldsOfExperts::FieldsOfExperts() : size_(0), num_filters_(0) {}
 
 bool FieldsOfExperts::LoadFromFile(const std::string& filename) {
   std::ifstream foe_file(filename.c_str());
@@ -147,6 +145,5 @@
   return new FieldsOfExpertsLoss(alpha_[alpha_index]);
 }
 
-
 }  // namespace examples
 }  // namespace ceres
diff --git a/examples/fields_of_experts.h b/examples/fields_of_experts.h
index 210ca69..429881d 100644
--- a/examples/fields_of_experts.h
+++ b/examples/fields_of_experts.h
@@ -47,10 +47,9 @@
 #include <iostream>
 #include <vector>
 
-#include "ceres/loss_function.h"
 #include "ceres/cost_function.h"
+#include "ceres/loss_function.h"
 #include "ceres/sized_cost_function.h"
-
 #include "pgm_image.h"
 
 namespace ceres {
@@ -78,7 +77,7 @@
 //
 class FieldsOfExpertsLoss : public ceres::LossFunction {
  public:
-  explicit FieldsOfExpertsLoss(double alpha) : alpha_(alpha) { }
+  explicit FieldsOfExpertsLoss(double alpha) : alpha_(alpha) {}
   virtual void Evaluate(double, double*) const;
 
  private:
@@ -97,19 +96,13 @@
   bool LoadFromFile(const std::string& filename);
 
   // Side length of a square filter in this FoE. They are all of the same size.
-  int Size() const {
-    return size_;
-  }
+  int Size() const { return size_; }
 
   // Total number of pixels the filter covers.
-  int NumVariables() const {
-    return size_ * size_;
-  }
+  int NumVariables() const { return size_ * size_; }
 
   // Number of filters used by the FoE.
-  int NumFilters() const {
-    return num_filters_;
-  }
+  int NumFilters() const { return num_filters_; }
 
   // Creates a new cost function. The caller is responsible for deallocating the
   // memory. alpha_index specifies which filter is used in the cost function.
@@ -119,12 +112,8 @@
   ceres::LossFunction* NewLossFunction(int alpha_index) const;
 
   // Gets the delta pixel indices for all pixels in a patch.
-  const std::vector<int>& GetXDeltaIndices() const {
-    return x_delta_indices_;
-  }
-  const std::vector<int>& GetYDeltaIndices() const {
-    return y_delta_indices_;
-  }
+  const std::vector<int>& GetXDeltaIndices() const { return x_delta_indices_; }
+  const std::vector<int>& GetYDeltaIndices() const { return y_delta_indices_; }
 
  private:
   // The side length of a square filter.
@@ -136,7 +125,7 @@
   // The coefficients in front of each term.
   std::vector<double> alpha_;
   // The filters used for the dot product with image patches.
-  std::vector<std::vector<double> > filters_;
+  std::vector<std::vector<double>> filters_;
 };
 
 }  // namespace examples
diff --git a/examples/helloworld.cc b/examples/helloworld.cc
index 22dff55..9e32fad 100644
--- a/examples/helloworld.cc
+++ b/examples/helloworld.cc
@@ -39,15 +39,16 @@
 using ceres::AutoDiffCostFunction;
 using ceres::CostFunction;
 using ceres::Problem;
-using ceres::Solver;
 using ceres::Solve;
+using ceres::Solver;
 
 // A templated cost functor that implements the residual r = 10 -
 // x. The method operator() is templated so that we can then use an
 // automatic differentiation wrapper around it to generate its
 // derivatives.
 struct CostFunctor {
-  template <typename T> bool operator()(const T* const x, T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x, T* residual) const {
     residual[0] = 10.0 - x[0];
     return true;
   }
@@ -68,7 +69,7 @@
   // auto-differentiation to obtain the derivative (jacobian).
   CostFunction* cost_function =
       new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
-  problem.AddResidualBlock(cost_function, NULL, &x);
+  problem.AddResidualBlock(cost_function, nullptr, &x);
 
   // Run the solver!
   Solver::Options options;
@@ -77,7 +78,6 @@
   Solve(options, &problem, &summary);
 
   std::cout << summary.BriefReport() << "\n";
-  std::cout << "x : " << initial_x
-            << " -> " << x << "\n";
+  std::cout << "x : " << initial_x << " -> " << x << "\n";
   return 0;
 }
diff --git a/examples/helloworld_analytic_diff.cc b/examples/helloworld_analytic_diff.cc
index 9dbbc76..6e120b5 100644
--- a/examples/helloworld_analytic_diff.cc
+++ b/examples/helloworld_analytic_diff.cc
@@ -33,20 +33,21 @@
 // Minimize 0.5 (10 - x)^2 using analytic jacobian matrix.
 
 #include <vector>
+
 #include "ceres/ceres.h"
 #include "glog/logging.h"
 
 using ceres::CostFunction;
-using ceres::SizedCostFunction;
 using ceres::Problem;
-using ceres::Solver;
+using ceres::SizedCostFunction;
 using ceres::Solve;
+using ceres::Solver;
 
 // A CostFunction implementing analytically derivatives for the
 // function f(x) = 10 - x.
 class QuadraticCostFunction
-  : public SizedCostFunction<1 /* number of residuals */,
-                             1 /* size of first parameter */> {
+    : public SizedCostFunction<1 /* number of residuals */,
+                               1 /* size of first parameter */> {
  public:
   virtual ~QuadraticCostFunction() {}
 
@@ -100,8 +101,7 @@
   Solve(options, &problem, &summary);
 
   std::cout << summary.BriefReport() << "\n";
-  std::cout << "x : " << initial_x
-            << " -> " << x << "\n";
+  std::cout << "x : " << initial_x << " -> " << x << "\n";
 
   return 0;
 }
diff --git a/examples/helloworld_numeric_diff.cc b/examples/helloworld_numeric_diff.cc
index 0810f47..474adf3 100644
--- a/examples/helloworld_numeric_diff.cc
+++ b/examples/helloworld_numeric_diff.cc
@@ -34,12 +34,12 @@
 #include "ceres/ceres.h"
 #include "glog/logging.h"
 
-using ceres::NumericDiffCostFunction;
 using ceres::CENTRAL;
 using ceres::CostFunction;
+using ceres::NumericDiffCostFunction;
 using ceres::Problem;
-using ceres::Solver;
 using ceres::Solve;
+using ceres::Solver;
 
 // A cost functor that implements the residual r = 10 - x.
 struct CostFunctor {
@@ -63,7 +63,7 @@
   // Set up the only cost function (also known as residual). This uses
   // numeric differentiation to obtain the derivative (jacobian).
   CostFunction* cost_function =
-      new NumericDiffCostFunction<CostFunctor, CENTRAL, 1, 1> (new CostFunctor);
+      new NumericDiffCostFunction<CostFunctor, CENTRAL, 1, 1>(new CostFunctor);
   problem.AddResidualBlock(cost_function, NULL, &x);
 
   // Run the solver!
@@ -73,7 +73,6 @@
   Solve(options, &problem, &summary);
 
   std::cout << summary.BriefReport() << "\n";
-  std::cout << "x : " << initial_x
-            << " -> " << x << "\n";
+  std::cout << "x : " << initial_x << " -> " << x << "\n";
   return 0;
 }
diff --git a/examples/libmv_bundle_adjuster.cc b/examples/libmv_bundle_adjuster.cc
index 47d0cd7..b1eb220 100644
--- a/examples/libmv_bundle_adjuster.cc
+++ b/examples/libmv_bundle_adjuster.cc
@@ -87,16 +87,17 @@
 // There're existing problem files dumped from blender stored in folder
 // ../data/libmv-ba-problems.
 
-#include <cstdio>
 #include <fcntl.h>
+
+#include <cstdio>
 #include <sstream>
 #include <string>
 #include <vector>
 
 #ifdef _MSC_VER
-#  include <io.h>
-#  define open _open
-#  define close _close
+#include <io.h>
+#define open _open
+#define close _close
 typedef unsigned __int32 uint32_t;
 #else
 #include <stdint.h>
@@ -121,8 +122,9 @@
 using std::vector;
 
 DEFINE_string(input, "", "Input File name");
-DEFINE_string(refine_intrinsics, "", "Camera intrinsics to be refined. "
-              "Options are: none, radial.");
+DEFINE_string(refine_intrinsics,
+              "",
+              "Camera intrinsics to be refined. Options are: none, radial.");
 
 namespace {
 
@@ -134,7 +136,7 @@
 // t is a translation vector representing its positions.
 struct EuclideanCamera {
   EuclideanCamera() : image(-1) {}
-  EuclideanCamera(const EuclideanCamera &c) : image(c.image), R(c.R), t(c.t) {}
+  EuclideanCamera(const EuclideanCamera& c) : image(c.image), R(c.R), t(c.t) {}
 
   int image;
   Mat3 R;
@@ -147,7 +149,7 @@
 // X represents the 3D position of the track.
 struct EuclideanPoint {
   EuclideanPoint() : track(-1) {}
-  EuclideanPoint(const EuclideanPoint &p) : track(p.track), X(p.X) {}
+  EuclideanPoint(const EuclideanPoint& p) : track(p.track), X(p.X) {}
   int track;
   Vec3 X;
 };
@@ -201,25 +203,24 @@
 };
 
 // Returns a pointer to the camera corresponding to a image.
-EuclideanCamera *CameraForImage(vector<EuclideanCamera> *all_cameras,
+EuclideanCamera* CameraForImage(vector<EuclideanCamera>* all_cameras,
                                 const int image) {
   if (image < 0 || image >= all_cameras->size()) {
     return NULL;
   }
-  EuclideanCamera *camera = &(*all_cameras)[image];
+  EuclideanCamera* camera = &(*all_cameras)[image];
   if (camera->image == -1) {
     return NULL;
   }
   return camera;
 }
 
-const EuclideanCamera *CameraForImage(
-    const vector<EuclideanCamera> &all_cameras,
-    const int image) {
+const EuclideanCamera* CameraForImage(
+    const vector<EuclideanCamera>& all_cameras, const int image) {
   if (image < 0 || image >= all_cameras.size()) {
     return NULL;
   }
-  const EuclideanCamera *camera = &all_cameras[image];
+  const EuclideanCamera* camera = &all_cameras[image];
   if (camera->image == -1) {
     return NULL;
   }
@@ -227,7 +228,7 @@
 }
 
 // Returns maximal image number at which marker exists.
-int MaxImage(const vector<Marker> &all_markers) {
+int MaxImage(const vector<Marker>& all_markers) {
   if (all_markers.size() == 0) {
     return -1;
   }
@@ -240,12 +241,12 @@
 }
 
 // Returns a pointer to the point corresponding to a track.
-EuclideanPoint *PointForTrack(vector<EuclideanPoint> *all_points,
+EuclideanPoint* PointForTrack(vector<EuclideanPoint>* all_points,
                               const int track) {
   if (track < 0 || track >= all_points->size()) {
     return NULL;
   }
-  EuclideanPoint *point = &(*all_points)[track];
+  EuclideanPoint* point = &(*all_points)[track];
   if (point->track == -1) {
     return NULL;
   }
@@ -266,7 +267,7 @@
     union {
       unsigned char bytes[4];
       uint32_t value;
-    } endian_test = { { 0, 1, 2, 3 } };
+    } endian_test = {{0, 1, 2, 3}};
     host_endian_type_ = endian_test.value;
     file_endian_type_ = host_endian_type_;
   }
@@ -277,7 +278,7 @@
     }
   }
 
-  bool OpenFile(const std::string &file_name) {
+  bool OpenFile(const std::string& file_name) {
     file_descriptor_ = open(file_name.c_str(), O_RDONLY | O_BINARY);
     if (file_descriptor_ < 0) {
       return false;
@@ -306,23 +307,27 @@
     }
     return value;
   }
+
  private:
-  static const long int kLittleEndian = 0x03020100ul;
-  static const long int kBigEndian = 0x00010203ul;
+  static constexpr long int kLittleEndian = 0x03020100ul;
+  static constexpr long int kBigEndian = 0x00010203ul;
 
   // Switch endian type between big to little.
   template <typename T>
   T SwitchEndian(const T value) const {
     if (sizeof(T) == 4) {
       unsigned int temp_value = static_cast<unsigned int>(value);
+      // clang-format off
       return ((temp_value >> 24)) |
              ((temp_value << 8) & 0x00ff0000) |
              ((temp_value >> 8) & 0x0000ff00) |
              ((temp_value << 24));
+      // clang-format on
     } else if (sizeof(T) == 1) {
       return value;
     } else {
-      LOG(FATAL) << "Entered non-implemented part of endian switching function.";
+      LOG(FATAL) << "Entered non-implemented part of endian "
+                    "switching function.";
     }
   }
 
@@ -332,16 +337,14 @@
 };
 
 // Read 3x3 column-major matrix from the file
-void ReadMatrix3x3(const EndianAwareFileReader &file_reader,
-                   Mat3 *matrix) {
+void ReadMatrix3x3(const EndianAwareFileReader& file_reader, Mat3* matrix) {
   for (int i = 0; i < 9; i++) {
     (*matrix)(i % 3, i / 3) = file_reader.Read<float>();
   }
 }
 
 // Read 3-vector from file
-void ReadVector3(const EndianAwareFileReader &file_reader,
-                 Vec3 *vector) {
+void ReadVector3(const EndianAwareFileReader& file_reader, Vec3* vector) {
   for (int i = 0; i < 3; i++) {
     (*vector)(i) = file_reader.Read<float>();
   }
@@ -364,12 +367,12 @@
 //
 // Returns false if any kind of error happened during
 // reading.
-bool ReadProblemFromFile(const std::string &file_name,
+bool ReadProblemFromFile(const std::string& file_name,
                          double camera_intrinsics[8],
-                         vector<EuclideanCamera> *all_cameras,
-                         vector<EuclideanPoint> *all_points,
-                         bool *is_image_space,
-                         vector<Marker> *all_markers) {
+                         vector<EuclideanCamera>* all_cameras,
+                         vector<EuclideanPoint>* all_points,
+                         bool* is_image_space,
+                         vector<Marker>* all_markers) {
   EndianAwareFileReader file_reader;
   if (!file_reader.OpenFile(file_name)) {
     return false;
@@ -451,24 +454,24 @@
 // camera coordinates (i.e. the principal point is at (0, 0)) to get image
 // coordinates in pixels. Templated for use with autodifferentiation.
 template <typename T>
-inline void ApplyRadialDistortionCameraIntrinsics(const T &focal_length_x,
-                                                  const T &focal_length_y,
-                                                  const T &principal_point_x,
-                                                  const T &principal_point_y,
-                                                  const T &k1,
-                                                  const T &k2,
-                                                  const T &k3,
-                                                  const T &p1,
-                                                  const T &p2,
-                                                  const T &normalized_x,
-                                                  const T &normalized_y,
-                                                  T *image_x,
-                                                  T *image_y) {
+inline void ApplyRadialDistortionCameraIntrinsics(const T& focal_length_x,
+                                                  const T& focal_length_y,
+                                                  const T& principal_point_x,
+                                                  const T& principal_point_y,
+                                                  const T& k1,
+                                                  const T& k2,
+                                                  const T& k3,
+                                                  const T& p1,
+                                                  const T& p2,
+                                                  const T& normalized_x,
+                                                  const T& normalized_y,
+                                                  T* image_x,
+                                                  T* image_y) {
   T x = normalized_x;
   T y = normalized_y;
 
   // Apply distortion to the normalized points to get (xd, yd).
-  T r2 = x*x + y*y;
+  T r2 = x * x + y * y;
   T r4 = r2 * r2;
   T r6 = r4 * r2;
   T r_coeff = 1.0 + k1 * r2 + k2 * r4 + k3 * r6;
@@ -496,14 +499,14 @@
                   const T* const X,    // Point coordinates 3x1.
                   T* residuals) const {
     // Unpack the intrinsics.
-    const T& focal_length      = intrinsics[OFFSET_FOCAL_LENGTH];
+    const T& focal_length = intrinsics[OFFSET_FOCAL_LENGTH];
     const T& principal_point_x = intrinsics[OFFSET_PRINCIPAL_POINT_X];
     const T& principal_point_y = intrinsics[OFFSET_PRINCIPAL_POINT_Y];
-    const T& k1                = intrinsics[OFFSET_K1];
-    const T& k2                = intrinsics[OFFSET_K2];
-    const T& k3                = intrinsics[OFFSET_K3];
-    const T& p1                = intrinsics[OFFSET_P1];
-    const T& p2                = intrinsics[OFFSET_P2];
+    const T& k1 = intrinsics[OFFSET_K1];
+    const T& k2 = intrinsics[OFFSET_K2];
+    const T& k3 = intrinsics[OFFSET_K3];
+    const T& p1 = intrinsics[OFFSET_P1];
+    const T& p2 = intrinsics[OFFSET_P2];
 
     // Compute projective coordinates: x = RX + t.
     T x[3];
@@ -526,9 +529,13 @@
                                           focal_length,
                                           principal_point_x,
                                           principal_point_y,
-                                          k1, k2, k3,
-                                          p1, p2,
-                                          xn, yn,
+                                          k1,
+                                          k2,
+                                          k3,
+                                          p1,
+                                          p2,
+                                          xn,
+                                          yn,
                                           &predicted_x,
                                           &predicted_y);
 
@@ -551,40 +558,41 @@
     std::string bundling_message = "";
 
 #define APPEND_BUNDLING_INTRINSICS(name, flag) \
-    if (bundle_intrinsics & flag) { \
-      if (!bundling_message.empty()) { \
-        bundling_message += ", "; \
-      } \
-      bundling_message += name; \
-    } (void)0
+  if (bundle_intrinsics & flag) {              \
+    if (!bundling_message.empty()) {           \
+      bundling_message += ", ";                \
+    }                                          \
+    bundling_message += name;                  \
+  }                                            \
+  (void)0
 
-    APPEND_BUNDLING_INTRINSICS("f",      BUNDLE_FOCAL_LENGTH);
+    APPEND_BUNDLING_INTRINSICS("f", BUNDLE_FOCAL_LENGTH);
     APPEND_BUNDLING_INTRINSICS("px, py", BUNDLE_PRINCIPAL_POINT);
-    APPEND_BUNDLING_INTRINSICS("k1",     BUNDLE_RADIAL_K1);
-    APPEND_BUNDLING_INTRINSICS("k2",     BUNDLE_RADIAL_K2);
-    APPEND_BUNDLING_INTRINSICS("p1",     BUNDLE_TANGENTIAL_P1);
-    APPEND_BUNDLING_INTRINSICS("p2",     BUNDLE_TANGENTIAL_P2);
+    APPEND_BUNDLING_INTRINSICS("k1", BUNDLE_RADIAL_K1);
+    APPEND_BUNDLING_INTRINSICS("k2", BUNDLE_RADIAL_K2);
+    APPEND_BUNDLING_INTRINSICS("p1", BUNDLE_TANGENTIAL_P1);
+    APPEND_BUNDLING_INTRINSICS("p2", BUNDLE_TANGENTIAL_P2);
 
     LOG(INFO) << "Bundling " << bundling_message << ".";
   }
 }
 
 // Print a message to the log containing all the camera intriniscs values.
-void PrintCameraIntrinsics(const char *text, const double *camera_intrinsics) {
+void PrintCameraIntrinsics(const char* text, const double* camera_intrinsics) {
   std::ostringstream intrinsics_output;
 
   intrinsics_output << "f=" << camera_intrinsics[OFFSET_FOCAL_LENGTH];
 
-  intrinsics_output <<
-    " cx=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_X] <<
-    " cy=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_Y];
+  intrinsics_output << " cx=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_X]
+                    << " cy=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_Y];
 
-#define APPEND_DISTORTION_COEFFICIENT(name, offset) \
-  { \
-    if (camera_intrinsics[offset] != 0.0) { \
-      intrinsics_output << " " name "=" << camera_intrinsics[offset];  \
-    } \
-  } (void)0
+#define APPEND_DISTORTION_COEFFICIENT(name, offset)                   \
+  {                                                                   \
+    if (camera_intrinsics[offset] != 0.0) {                           \
+      intrinsics_output << " " name "=" << camera_intrinsics[offset]; \
+    }                                                                 \
+  }                                                                   \
+  (void)0
 
   APPEND_DISTORTION_COEFFICIENT("k1", OFFSET_K1);
   APPEND_DISTORTION_COEFFICIENT("k2", OFFSET_K2);
@@ -603,22 +611,21 @@
 // Element with index i matches to a rotation+translation for
 // camera at image i.
 vector<Vec6> PackCamerasRotationAndTranslation(
-    const vector<Marker> &all_markers,
-    const vector<EuclideanCamera> &all_cameras) {
+    const vector<Marker>& all_markers,
+    const vector<EuclideanCamera>& all_cameras) {
   vector<Vec6> all_cameras_R_t;
   int max_image = MaxImage(all_markers);
 
   all_cameras_R_t.resize(max_image + 1);
 
   for (int i = 0; i <= max_image; i++) {
-    const EuclideanCamera *camera = CameraForImage(all_cameras, i);
+    const EuclideanCamera* camera = CameraForImage(all_cameras, i);
 
     if (!camera) {
       continue;
     }
 
-    ceres::RotationMatrixToAngleAxis(&camera->R(0, 0),
-                                     &all_cameras_R_t[i](0));
+    ceres::RotationMatrixToAngleAxis(&camera->R(0, 0), &all_cameras_R_t[i](0));
     all_cameras_R_t[i].tail<3>() = camera->t;
   }
 
@@ -626,34 +633,33 @@
 }
 
 // Convert cameras rotations fro mangle axis back to rotation matrix.
-void UnpackCamerasRotationAndTranslation(
-    const vector<Marker> &all_markers,
-    const vector<Vec6> &all_cameras_R_t,
-    vector<EuclideanCamera> *all_cameras) {
+void UnpackCamerasRotationAndTranslation(const vector<Marker>& all_markers,
+                                         const vector<Vec6>& all_cameras_R_t,
+                                         vector<EuclideanCamera>* all_cameras) {
   int max_image = MaxImage(all_markers);
 
   for (int i = 0; i <= max_image; i++) {
-    EuclideanCamera *camera = CameraForImage(all_cameras, i);
+    EuclideanCamera* camera = CameraForImage(all_cameras, i);
 
     if (!camera) {
       continue;
     }
 
-    ceres::AngleAxisToRotationMatrix(&all_cameras_R_t[i](0),
-                                     &camera->R(0, 0));
+    ceres::AngleAxisToRotationMatrix(&all_cameras_R_t[i](0), &camera->R(0, 0));
     camera->t = all_cameras_R_t[i].tail<3>();
   }
 }
 
-void EuclideanBundleCommonIntrinsics(const vector<Marker> &all_markers,
+void EuclideanBundleCommonIntrinsics(const vector<Marker>& all_markers,
                                      const int bundle_intrinsics,
                                      const int bundle_constraints,
-                                     double *camera_intrinsics,
-                                     vector<EuclideanCamera> *all_cameras,
-                                     vector<EuclideanPoint> *all_points) {
+                                     double* camera_intrinsics,
+                                     vector<EuclideanCamera>* all_cameras,
+                                     vector<EuclideanPoint>* all_points) {
   PrintCameraIntrinsics("Original intrinsics: ", camera_intrinsics);
 
   ceres::Problem::Options problem_options;
+  problem_options.cost_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP;
   ceres::Problem problem(problem_options);
 
   // Convert cameras rotations to angle axis and merge with translation
@@ -662,45 +668,50 @@
   // Block for minimization has got the following structure:
   //   <3 elements for angle-axis> <3 elements for translation>
   vector<Vec6> all_cameras_R_t =
-    PackCamerasRotationAndTranslation(all_markers, *all_cameras);
+      PackCamerasRotationAndTranslation(all_markers, *all_cameras);
 
   // Parameterization used to restrict camera motion for modal solvers.
-  ceres::SubsetParameterization *constant_transform_parameterization = NULL;
+  ceres::SubsetParameterization* constant_transform_parameterization = NULL;
   if (bundle_constraints & BUNDLE_NO_TRANSLATION) {
-      std::vector<int> constant_translation;
+    std::vector<int> constant_translation;
 
-      // First three elements are rotation, last three are translation.
-      constant_translation.push_back(3);
-      constant_translation.push_back(4);
-      constant_translation.push_back(5);
+    // First three elements are rotation, last three are translation.
+    constant_translation.push_back(3);
+    constant_translation.push_back(4);
+    constant_translation.push_back(5);
 
-      constant_transform_parameterization =
+    constant_transform_parameterization =
         new ceres::SubsetParameterization(6, constant_translation);
   }
 
+  std::vector<OpenCVReprojectionError> errors;
+  std::vector<ceres::AutoDiffCostFunction<OpenCVReprojectionError, 2, 8, 6, 3>>
+      costFunctions;
+  errors.reserve(all_markers.size());
+  costFunctions.reserve(all_markers.size());
+
   int num_residuals = 0;
   bool have_locked_camera = false;
   for (int i = 0; i < all_markers.size(); ++i) {
-    const Marker &marker = all_markers[i];
-    EuclideanCamera *camera = CameraForImage(all_cameras, marker.image);
-    EuclideanPoint *point = PointForTrack(all_points, marker.track);
+    const Marker& marker = all_markers[i];
+    EuclideanCamera* camera = CameraForImage(all_cameras, marker.image);
+    EuclideanPoint* point = PointForTrack(all_points, marker.track);
     if (camera == NULL || point == NULL) {
       continue;
     }
 
     // Rotation of camera denoted in angle axis followed with
     // camera translaiton.
-    double *current_camera_R_t = &all_cameras_R_t[camera->image](0);
+    double* current_camera_R_t = &all_cameras_R_t[camera->image](0);
 
-    problem.AddResidualBlock(new ceres::AutoDiffCostFunction<
-        OpenCVReprojectionError, 2, 8, 6, 3>(
-            new OpenCVReprojectionError(
-                marker.x,
-                marker.y)),
-        NULL,
-        camera_intrinsics,
-        current_camera_R_t,
-        &point->X(0));
+    errors.emplace_back(marker.x, marker.y);
+    costFunctions.emplace_back(&errors.back(), ceres::DO_NOT_TAKE_OWNERSHIP);
+
+    problem.AddResidualBlock(&costFunctions.back(),
+                             NULL,
+                             camera_intrinsics,
+                             current_camera_R_t,
+                             &point->X(0));
 
     // We lock the first camera to better deal with scene orientation ambiguity.
     if (!have_locked_camera) {
@@ -734,23 +745,23 @@
 
     std::vector<int> constant_intrinsics;
 #define MAYBE_SET_CONSTANT(bundle_enum, offset) \
-    if (!(bundle_intrinsics & bundle_enum)) { \
-      constant_intrinsics.push_back(offset); \
-    }
-    MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH,    OFFSET_FOCAL_LENGTH);
+  if (!(bundle_intrinsics & bundle_enum)) {     \
+    constant_intrinsics.push_back(offset);      \
+  }
+    MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH, OFFSET_FOCAL_LENGTH);
     MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_X);
     MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_Y);
-    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1,       OFFSET_K1);
-    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2,       OFFSET_K2);
-    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1,   OFFSET_P1);
-    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2,   OFFSET_P2);
+    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1, OFFSET_K1);
+    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2, OFFSET_K2);
+    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1, OFFSET_P1);
+    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2, OFFSET_P2);
 #undef MAYBE_SET_CONSTANT
 
     // Always set K3 constant, it's not used at the moment.
     constant_intrinsics.push_back(OFFSET_K3);
 
-    ceres::SubsetParameterization *subset_parameterization =
-      new ceres::SubsetParameterization(8, constant_intrinsics);
+    ceres::SubsetParameterization* subset_parameterization =
+        new ceres::SubsetParameterization(8, constant_intrinsics);
 
     problem.SetParameterization(camera_intrinsics, subset_parameterization);
   }
@@ -771,16 +782,15 @@
   std::cout << "Final report:\n" << summary.FullReport();
 
   // Copy rotations and translations back.
-  UnpackCamerasRotationAndTranslation(all_markers,
-                                      all_cameras_R_t,
-                                      all_cameras);
+  UnpackCamerasRotationAndTranslation(
+      all_markers, all_cameras_R_t, all_cameras);
 
   PrintCameraIntrinsics("Final intrinsics: ", camera_intrinsics);
 }
 }  // namespace
 
-int main(int argc, char **argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+int main(int argc, char** argv) {
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
 
   if (FLAGS_input.empty()) {
diff --git a/examples/libmv_homography.cc b/examples/libmv_homography.cc
index fe647da..55f3b70 100644
--- a/examples/libmv_homography.cc
+++ b/examples/libmv_homography.cc
@@ -54,8 +54,8 @@
 // homogeneous system of equations via singular value decomposition, giving an
 // algebraic solution for the homography, then solving for a final solution by
 // minimizing the symmetric transfer error in image space with Ceres (called the
-// Gold Standard Solution in "Multiple View Geometry"). The routines are based on
-// the routines from the Libmv library.
+// Gold Standard Solution in "Multiple View Geometry"). The routines are based
+// on the routines from the Libmv library.
 //
 // This example demonstrates custom exit criterion by having a callback check
 // for image-space error.
@@ -69,7 +69,7 @@
 typedef Eigen::VectorXd Vec;
 typedef Eigen::Matrix<double, 3, 3> Mat3;
 typedef Eigen::Matrix<double, 2, 1> Vec2;
-typedef Eigen::Matrix<double, Eigen::Dynamic,  8> MatX8;
+typedef Eigen::Matrix<double, Eigen::Dynamic, 8> MatX8;
 typedef Eigen::Vector3d Vec3;
 
 namespace {
@@ -83,8 +83,7 @@
   // Default settings for homography estimation which should be suitable
   // for a wide range of use cases.
   EstimateHomographyOptions()
-    :  max_num_iterations(50),
-       expected_average_symmetric_distance(1e-16) {}
+      : max_num_iterations(50), expected_average_symmetric_distance(1e-16) {}
 
   // Maximal number of iterations for the refinement step.
   int max_num_iterations;
@@ -107,9 +106,9 @@
 //
 // Templated to be used with autodifferentiation.
 template <typename T>
-void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3> &H,
-                                     const Eigen::Matrix<T, 2, 1> &x1,
-                                     const Eigen::Matrix<T, 2, 1> &x2,
+void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3>& H,
+                                     const Eigen::Matrix<T, 2, 1>& x1,
+                                     const Eigen::Matrix<T, 2, 1>& x2,
                                      T forward_error[2],
                                      T backward_error[2]) {
   typedef Eigen::Matrix<T, 3, 1> Vec3;
@@ -132,17 +131,13 @@
 //
 //   D(H * x1, x2)^2 + D(H^-1 * x2, x1)^2
 //
-double SymmetricGeometricDistance(const Mat3 &H,
-                                  const Vec2 &x1,
-                                  const Vec2 &x2) {
+double SymmetricGeometricDistance(const Mat3& H,
+                                  const Vec2& x1,
+                                  const Vec2& x2) {
   Vec2 forward_error, backward_error;
-  SymmetricGeometricDistanceTerms<double>(H,
-                                          x1,
-                                          x2,
-                                          forward_error.data(),
-                                          backward_error.data());
-  return forward_error.squaredNorm() +
-         backward_error.squaredNorm();
+  SymmetricGeometricDistanceTerms<double>(
+      H, x1, x2, forward_error.data(), backward_error.data());
+  return forward_error.squaredNorm() + backward_error.squaredNorm();
 }
 
 // A parameterization of the 2D homography matrix that uses 8 parameters so
@@ -154,24 +149,28 @@
 //     H = |d e f|
 //         |g h 1|
 //
-template<typename T = double>
+template <typename T = double>
 class Homography2DNormalizedParameterization {
  public:
   typedef Eigen::Matrix<T, 8, 1> Parameters;     // a, b, ... g, h
   typedef Eigen::Matrix<T, 3, 3> Parameterized;  // H
 
   // Convert from the 8 parameters to a H matrix.
-  static void To(const Parameters &p, Parameterized *h) {
+  static void To(const Parameters& p, Parameterized* h) {
+    // clang-format off
     *h << p(0), p(1), p(2),
           p(3), p(4), p(5),
           p(6), p(7), 1.0;
+    // clang-format on
   }
 
   // Convert from a H matrix to the 8 parameters.
-  static void From(const Parameterized &h, Parameters *p) {
+  static void From(const Parameterized& h, Parameters* p) {
+    // clang-format off
     *p << h(0, 0), h(0, 1), h(0, 2),
           h(1, 0), h(1, 1), h(1, 2),
           h(2, 0), h(2, 1);
+    // clang-format on
   }
 };
 
@@ -194,11 +193,10 @@
 //   (a-x1*g)*y1     + (b-x1*h)*y2  + c-x1         = |0|
 //   (-x2*a+x1*d)*y1 + (-x2*b+x1*e)*y2 + -x2*c+x1*f  |0|
 //
-bool Homography2DFromCorrespondencesLinearEuc(
-    const Mat &x1,
-    const Mat &x2,
-    Mat3 *H,
-    double expected_precision) {
+bool Homography2DFromCorrespondencesLinearEuc(const Mat& x1,
+                                              const Mat& x2,
+                                              Mat3* H,
+                                              double expected_precision) {
   assert(2 == x1.rows());
   assert(4 <= x1.cols());
   assert(x1.rows() == x2.rows());
@@ -209,27 +207,27 @@
   Mat b = Mat::Zero(n * 3, 1);
   for (int i = 0; i < n; ++i) {
     int j = 3 * i;
-    L(j, 0) =  x1(0, i);             // a
-    L(j, 1) =  x1(1, i);             // b
-    L(j, 2) =  1.0;                  // c
+    L(j, 0) = x1(0, i);              // a
+    L(j, 1) = x1(1, i);              // b
+    L(j, 2) = 1.0;                   // c
     L(j, 6) = -x2(0, i) * x1(0, i);  // g
     L(j, 7) = -x2(0, i) * x1(1, i);  // h
-    b(j, 0) =  x2(0, i);             // i
+    b(j, 0) = x2(0, i);              // i
 
     ++j;
-    L(j, 3) =  x1(0, i);             // d
-    L(j, 4) =  x1(1, i);             // e
-    L(j, 5) =  1.0;                  // f
+    L(j, 3) = x1(0, i);              // d
+    L(j, 4) = x1(1, i);              // e
+    L(j, 5) = 1.0;                   // f
     L(j, 6) = -x2(1, i) * x1(0, i);  // g
     L(j, 7) = -x2(1, i) * x1(1, i);  // h
-    b(j, 0) =  x2(1, i);             // i
+    b(j, 0) = x2(1, i);              // i
 
     // This ensures better stability
     // TODO(julien) make a lite version without this 3rd set
     ++j;
-    L(j, 0) =  x2(1, i) * x1(0, i);  // a
-    L(j, 1) =  x2(1, i) * x1(1, i);  // b
-    L(j, 2) =  x2(1, i);             // c
+    L(j, 0) = x2(1, i) * x1(0, i);   // a
+    L(j, 1) = x2(1, i) * x1(1, i);   // b
+    L(j, 2) = x2(1, i);              // c
     L(j, 3) = -x2(0, i) * x1(0, i);  // d
     L(j, 4) = -x2(0, i) * x1(1, i);  // e
     L(j, 5) = -x2(0, i);             // f
@@ -244,11 +242,10 @@
 // used for homography matrix refinement.
 class HomographySymmetricGeometricCostFunctor {
  public:
-  HomographySymmetricGeometricCostFunctor(const Vec2 &x,
-                                          const Vec2 &y)
-      : x_(x), y_(y) { }
+  HomographySymmetricGeometricCostFunctor(const Vec2& x, const Vec2& y)
+      : x_(x), y_(y) {}
 
-  template<typename T>
+  template <typename T>
   bool operator()(const T* homography_parameters, T* residuals) const {
     typedef Eigen::Matrix<T, 3, 3> Mat3;
     typedef Eigen::Matrix<T, 2, 1> Vec2;
@@ -257,11 +254,7 @@
     Vec2 x(T(x_(0)), T(x_(1)));
     Vec2 y(T(y_(0)), T(y_(1)));
 
-    SymmetricGeometricDistanceTerms<T>(H,
-                                       x,
-                                       y,
-                                       &residuals[0],
-                                       &residuals[2]);
+    SymmetricGeometricDistanceTerms<T>(H, x, y, &residuals[0], &residuals[2]);
     return true;
   }
 
@@ -278,9 +271,10 @@
 // points < 0.5px error).
 class TerminationCheckingCallback : public ceres::IterationCallback {
  public:
-  TerminationCheckingCallback(const Mat &x1, const Mat &x2,
-                              const EstimateHomographyOptions &options,
-                              Mat3 *H)
+  TerminationCheckingCallback(const Mat& x1,
+                              const Mat& x2,
+                              const EstimateHomographyOptions& options,
+                              Mat3* H)
       : options_(options), x1_(x1), x2_(x2), H_(H) {}
 
   virtual ceres::CallbackReturnType operator()(
@@ -293,9 +287,8 @@
     // Calculate average of symmetric geometric distance.
     double average_distance = 0.0;
     for (int i = 0; i < x1_.cols(); i++) {
-      average_distance += SymmetricGeometricDistance(*H_,
-                                                     x1_.col(i),
-                                                     x2_.col(i));
+      average_distance +=
+          SymmetricGeometricDistance(*H_, x1_.col(i), x2_.col(i));
     }
     average_distance /= x1_.cols();
 
@@ -307,17 +300,17 @@
   }
 
  private:
-  const EstimateHomographyOptions &options_;
-  const Mat &x1_;
-  const Mat &x2_;
-  Mat3 *H_;
+  const EstimateHomographyOptions& options_;
+  const Mat& x1_;
+  const Mat& x2_;
+  Mat3* H_;
 };
 
 bool EstimateHomography2DFromCorrespondences(
-    const Mat &x1,
-    const Mat &x2,
-    const EstimateHomographyOptions &options,
-    Mat3 *H) {
+    const Mat& x1,
+    const Mat& x2,
+    const EstimateHomographyOptions& options,
+    Mat3* H) {
   assert(2 == x1.rows());
   assert(4 <= x1.cols());
   assert(x1.rows() == x2.rows());
@@ -325,26 +318,23 @@
 
   // Step 1: Algebraic homography estimation.
   // Assume algebraic estimation always succeeds.
-  Homography2DFromCorrespondencesLinearEuc(x1,
-                                           x2,
-                                           H,
-                                           EigenDouble::dummy_precision());
+  Homography2DFromCorrespondencesLinearEuc(
+      x1, x2, H, EigenDouble::dummy_precision());
 
   LOG(INFO) << "Estimated matrix after algebraic estimation:\n" << *H;
 
   // Step 2: Refine matrix using Ceres minimizer.
   ceres::Problem problem;
   for (int i = 0; i < x1.cols(); i++) {
-    HomographySymmetricGeometricCostFunctor
-        *homography_symmetric_geometric_cost_function =
-            new HomographySymmetricGeometricCostFunctor(x1.col(i),
-                                                        x2.col(i));
+    HomographySymmetricGeometricCostFunctor*
+        homography_symmetric_geometric_cost_function =
+            new HomographySymmetricGeometricCostFunctor(x1.col(i), x2.col(i));
 
     problem.AddResidualBlock(
-        new ceres::AutoDiffCostFunction<
-            HomographySymmetricGeometricCostFunctor,
-            4,  // num_residuals
-            9>(homography_symmetric_geometric_cost_function),
+        new ceres::AutoDiffCostFunction<HomographySymmetricGeometricCostFunctor,
+                                        4,  // num_residuals
+                                        9>(
+            homography_symmetric_geometric_cost_function),
         NULL,
         H->data());
   }
@@ -369,9 +359,9 @@
   return summary.IsSolutionUsable();
 }
 
-}  // namespace libmv
+}  // namespace
 
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);
 
   Mat x1(2, 100);
@@ -382,9 +372,11 @@
 
   Mat3 homography_matrix;
   // This matrix has been dumped from a Blender test file of plane tracking.
+  // clang-format off
   homography_matrix << 1.243715, -0.461057, -111.964454,
                        0.0,       0.617589, -192.379252,
                        0.0,      -0.000983,    1.0;
+  // clang-format on
 
   Mat x2 = x1;
   for (int i = 0; i < x2.cols(); ++i) {
@@ -405,7 +397,7 @@
   EstimateHomography2DFromCorrespondences(x1, x2, options, &estimated_matrix);
 
   // Normalize the matrix for easier comparison.
-  estimated_matrix /= estimated_matrix(2 ,2);
+  estimated_matrix /= estimated_matrix(2, 2);
 
   std::cout << "Original matrix:\n" << homography_matrix << "\n";
   std::cout << "Estimated matrix:\n" << estimated_matrix << "\n";
diff --git a/examples/more_garbow_hillstrom.cc b/examples/more_garbow_hillstrom.cc
index 02169cd..e39d23c 100644
--- a/examples/more_garbow_hillstrom.cc
+++ b/examples/more_garbow_hillstrom.cc
@@ -50,24 +50,27 @@
 // A problem is considered solved if of the log relative error of its
 // objective function is at least 4.
 
-
 #include <cmath>
 #include <iostream>  // NOLINT
 #include <sstream>   // NOLINT
 #include <string>
+
 #include "ceres/ceres.h"
 #include "gflags/gflags.h"
 #include "glog/logging.h"
 
 DEFINE_string(problem, "all", "Which problem to solve");
-DEFINE_bool(use_numeric_diff, false,
-            "Use numeric differentiation instead of automatic "
-            "differentiation.");
-DEFINE_string(numeric_diff_method, "ridders", "When using numeric "
-              "differentiation, selects algorithm. Options are: central, "
-              "forward, ridders.");
-DEFINE_int32(ridders_extrapolations, 3, "Maximal number of extrapolations in "
-             "Ridders' method.");
+DEFINE_bool(use_numeric_diff,
+            false,
+            "Use numeric differentiation instead of automatic"
+            " differentiation.");
+DEFINE_string(numeric_diff_method,
+              "ridders",
+              "When using numeric differentiation, selects algorithm. Options "
+              "are: central, forward, ridders.");
+DEFINE_int32(ridders_extrapolations,
+             3,
+             "Maximal number of extrapolations in Ridders' method.");
 
 namespace ceres {
 namespace examples {
@@ -78,48 +81,48 @@
   options->max_num_ridders_extrapolations = FLAGS_ridders_extrapolations;
 }
 
-#define BEGIN_MGH_PROBLEM(name, num_parameters, num_residuals)            \
-  struct name {                                                           \
-    static const int kNumParameters = num_parameters;                     \
-    static const double initial_x[kNumParameters];                        \
-    static const double lower_bounds[kNumParameters];                     \
-    static const double upper_bounds[kNumParameters];                     \
-    static const double constrained_optimal_cost;                         \
-    static const double unconstrained_optimal_cost;                       \
-    static CostFunction* Create() {                                       \
-      if (FLAGS_use_numeric_diff) {                                       \
-        ceres::NumericDiffOptions options;                                \
-        SetNumericDiffOptions(&options);                                  \
-        if (FLAGS_numeric_diff_method == "central") {                     \
-          return new NumericDiffCostFunction<name,                        \
-                                             ceres::CENTRAL,              \
-                                             num_residuals,               \
-                                             num_parameters>(             \
-              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);   \
-        } else if (FLAGS_numeric_diff_method == "forward") {              \
-          return new NumericDiffCostFunction<name,                        \
-                                             ceres::FORWARD,              \
-                                             num_residuals,               \
-                                             num_parameters>(             \
-              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);   \
-        } else if (FLAGS_numeric_diff_method == "ridders") {              \
-          return new NumericDiffCostFunction<name,                        \
-                                             ceres::RIDDERS,              \
-                                             num_residuals,               \
-                                             num_parameters>(             \
-              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);   \
-        } else {                                                          \
-          LOG(ERROR) << "Invalid numeric diff method specified";          \
-          return NULL;                                                    \
-        }                                                                 \
-      } else {                                                            \
-        return new AutoDiffCostFunction<name,                             \
-                                        num_residuals,                    \
-                                        num_parameters>(new name);        \
-      }                                                                   \
-    }                                                                     \
-    template <typename T>                                                 \
+#define BEGIN_MGH_PROBLEM(name, num_parameters, num_residuals)                \
+  struct name {                                                               \
+    static constexpr int kNumParameters = num_parameters;                     \
+    static const double initial_x[kNumParameters];                            \
+    static const double lower_bounds[kNumParameters];                         \
+    static const double upper_bounds[kNumParameters];                         \
+    static const double constrained_optimal_cost;                             \
+    static const double unconstrained_optimal_cost;                           \
+    static CostFunction* Create() {                                           \
+      if (FLAGS_use_numeric_diff) {                                           \
+        ceres::NumericDiffOptions options;                                    \
+        SetNumericDiffOptions(&options);                                      \
+        if (FLAGS_numeric_diff_method == "central") {                         \
+          return new NumericDiffCostFunction<name,                            \
+                                             ceres::CENTRAL,                  \
+                                             num_residuals,                   \
+                                             num_parameters>(                 \
+              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);       \
+        } else if (FLAGS_numeric_diff_method == "forward") {                  \
+          return new NumericDiffCostFunction<name,                            \
+                                             ceres::FORWARD,                  \
+                                             num_residuals,                   \
+                                             num_parameters>(                 \
+              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);       \
+        } else if (FLAGS_numeric_diff_method == "ridders") {                  \
+          return new NumericDiffCostFunction<name,                            \
+                                             ceres::RIDDERS,                  \
+                                             num_residuals,                   \
+                                             num_parameters>(                 \
+              new name, ceres::TAKE_OWNERSHIP, num_residuals, options);       \
+        } else {                                                              \
+          LOG(ERROR) << "Invalid numeric diff method specified";              \
+          return NULL;                                                        \
+        }                                                                     \
+      } else {                                                                \
+        return new AutoDiffCostFunction<name, num_residuals, num_parameters>( \
+            new name);                                                        \
+      }                                                                       \
+    }                                                                         \
+    template <typename T>                                                     \
     bool operator()(const T* const x, T* residual) const {
+// clang-format off
 
 #define END_MGH_PROBLEM return true; } };  // NOLINT
 
@@ -535,7 +538,10 @@
 #undef BEGIN_MGH_PROBLEM
 #undef END_MGH_PROBLEM
 
-template<typename TestProblem> bool Solve(bool is_constrained, int trial) {
+// clang-format on
+
+template <typename TestProblem>
+bool Solve(bool is_constrained, int trial) {
   double x[TestProblem::kNumParameters];
   for (int i = 0; i < TestProblem::kNumParameters; ++i) {
     x[i] = pow(10, trial) * TestProblem::initial_x[i];
@@ -563,16 +569,14 @@
   Solve(options, &problem, &summary);
 
   const double kMinLogRelativeError = 4.0;
-  const double log_relative_error = -std::log10(
-      std::abs(2.0 * summary.final_cost - optimal_cost) /
-      (optimal_cost > 0.0 ? optimal_cost : 1.0));
+  const double log_relative_error =
+      -std::log10(std::abs(2.0 * summary.final_cost - optimal_cost) /
+                  (optimal_cost > 0.0 ? optimal_cost : 1.0));
 
   const bool success = log_relative_error >= kMinLogRelativeError;
-  LOG(INFO) << "Expected : " <<  optimal_cost
-            << " actual: " << 2.0 * summary.final_cost
-            << " " << success
-            << " in " << summary.total_time_in_seconds
-            << " seconds";
+  LOG(INFO) << "Expected : " << optimal_cost
+            << " actual: " << 2.0 * summary.final_cost << " " << success
+            << " in " << summary.total_time_in_seconds << " seconds";
   return success;
 }
 
@@ -580,7 +584,7 @@
 }  // namespace ceres
 
 int main(int argc, char** argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
 
   using ceres::examples::Solve;
@@ -591,29 +595,29 @@
   int constrained_successes = 0;
   std::stringstream ss;
 
-#define UNCONSTRAINED_SOLVE(n)                                          \
-  ss << "Unconstrained Problem " << n << " : ";                          \
-  if (FLAGS_problem == #n || FLAGS_problem == "all") {                  \
-    unconstrained_problems += 3;                                        \
-    if (Solve<ceres::examples::TestProblem##n>(false, 0)) {             \
-      unconstrained_successes += 1;                                     \
-      ss <<  "Yes ";                                                    \
-    } else {                                                            \
-      ss << "No  ";                                                     \
-    }                                                                   \
-    if (Solve<ceres::examples::TestProblem##n>(false, 1)) {             \
-      unconstrained_successes += 1;                                     \
-      ss << "Yes ";                                                     \
-    } else {                                                            \
-      ss << "No  ";                                                     \
-    }                                                                   \
-    if (Solve<ceres::examples::TestProblem##n>(false, 2)) {             \
-      unconstrained_successes += 1;                                     \
-      ss << "Yes ";                                                     \
-    } else {                                                            \
-      ss << "No  ";                                                     \
-    }                                                                   \
-  }                                                                     \
+#define UNCONSTRAINED_SOLVE(n)                              \
+  ss << "Unconstrained Problem " << n << " : ";             \
+  if (FLAGS_problem == #n || FLAGS_problem == "all") {      \
+    unconstrained_problems += 3;                            \
+    if (Solve<ceres::examples::TestProblem##n>(false, 0)) { \
+      unconstrained_successes += 1;                         \
+      ss << "Yes ";                                         \
+    } else {                                                \
+      ss << "No  ";                                         \
+    }                                                       \
+    if (Solve<ceres::examples::TestProblem##n>(false, 1)) { \
+      unconstrained_successes += 1;                         \
+      ss << "Yes ";                                         \
+    } else {                                                \
+      ss << "No  ";                                         \
+    }                                                       \
+    if (Solve<ceres::examples::TestProblem##n>(false, 2)) { \
+      unconstrained_successes += 1;                         \
+      ss << "Yes ";                                         \
+    } else {                                                \
+      ss << "No  ";                                         \
+    }                                                       \
+  }                                                         \
   ss << std::endl;
 
   UNCONSTRAINED_SOLVE(1);
@@ -636,22 +640,20 @@
   UNCONSTRAINED_SOLVE(18);
   UNCONSTRAINED_SOLVE(19);
 
-  ss << "Unconstrained : "
-     << unconstrained_successes
-     << "/"
+  ss << "Unconstrained : " << unconstrained_successes << "/"
      << unconstrained_problems << std::endl;
 
-#define CONSTRAINED_SOLVE(n)                                            \
-  ss << "Constrained Problem " << n << " : ";                           \
-  if (FLAGS_problem == #n || FLAGS_problem == "all") {                  \
-    constrained_problems += 1;                                          \
-    if (Solve<ceres::examples::TestProblem##n>(true, 0)) {              \
-      constrained_successes += 1;                                       \
-      ss << "Yes ";                                                     \
-    } else {                                                            \
-      ss << "No  ";                                                     \
-    }                                                                   \
-  }                                                                     \
+#define CONSTRAINED_SOLVE(n)                               \
+  ss << "Constrained Problem " << n << " : ";              \
+  if (FLAGS_problem == #n || FLAGS_problem == "all") {     \
+    constrained_problems += 1;                             \
+    if (Solve<ceres::examples::TestProblem##n>(true, 0)) { \
+      constrained_successes += 1;                          \
+      ss << "Yes ";                                        \
+    } else {                                               \
+      ss << "No  ";                                        \
+    }                                                      \
+  }                                                        \
   ss << std::endl;
 
   CONSTRAINED_SOLVE(3);
@@ -664,10 +666,8 @@
   CONSTRAINED_SOLVE(14);
   CONSTRAINED_SOLVE(16);
   CONSTRAINED_SOLVE(18);
-  ss << "Constrained : "
-     << constrained_successes
-     << "/"
-     << constrained_problems << std::endl;
+  ss << "Constrained : " << constrained_successes << "/" << constrained_problems
+     << std::endl;
 
   std::cout << ss.str();
   return 0;
diff --git a/examples/nist.cc b/examples/nist.cc
index 8ce7291..977b69d 100644
--- a/examples/nist.cc
+++ b/examples/nist.cc
@@ -83,55 +83,74 @@
 #include "glog/logging.h"
 
 DEFINE_bool(use_tiny_solver, false, "Use TinySolver instead of Ceres::Solver");
-DEFINE_string(nist_data_dir, "", "Directory containing the NIST non-linear"
-              "regression examples");
-DEFINE_string(minimizer, "trust_region",
+DEFINE_string(nist_data_dir,
+              "",
+              "Directory containing the NIST non-linear regression examples");
+DEFINE_string(minimizer,
+              "trust_region",
               "Minimizer type to use, choices are: line_search & trust_region");
-DEFINE_string(trust_region_strategy, "levenberg_marquardt",
+DEFINE_string(trust_region_strategy,
+              "levenberg_marquardt",
               "Options are: levenberg_marquardt, dogleg");
-DEFINE_string(dogleg, "traditional_dogleg",
+DEFINE_string(dogleg,
+              "traditional_dogleg",
               "Options are: traditional_dogleg, subspace_dogleg");
-DEFINE_string(linear_solver, "dense_qr", "Options are: "
-              "sparse_cholesky, dense_qr, dense_normal_cholesky and"
-              "cgnr");
-DEFINE_string(preconditioner, "jacobi", "Options are: "
-              "identity, jacobi");
-DEFINE_string(line_search, "wolfe",
+DEFINE_string(linear_solver,
+              "dense_qr",
+              "Options are: sparse_cholesky, dense_qr, dense_normal_cholesky "
+              "and cgnr");
+DEFINE_string(preconditioner, "jacobi", "Options are: identity, jacobi");
+DEFINE_string(line_search,
+              "wolfe",
               "Line search algorithm to use, choices are: armijo and wolfe.");
-DEFINE_string(line_search_direction, "lbfgs",
+DEFINE_string(line_search_direction,
+              "lbfgs",
               "Line search direction algorithm to use, choices: lbfgs, bfgs");
-DEFINE_int32(max_line_search_iterations, 20,
+DEFINE_int32(max_line_search_iterations,
+             20,
              "Maximum number of iterations for each line search.");
-DEFINE_int32(max_line_search_restarts, 10,
+DEFINE_int32(max_line_search_restarts,
+             10,
              "Maximum number of restarts of line search direction algorithm.");
-DEFINE_string(line_search_interpolation, "cubic",
-              "Degree of polynomial aproximation in line search, "
-              "choices are: bisection, quadratic & cubic.");
-DEFINE_int32(lbfgs_rank, 20,
+DEFINE_string(line_search_interpolation,
+              "cubic",
+              "Degree of polynomial aproximation in line search, choices are: "
+              "bisection, quadratic & cubic.");
+DEFINE_int32(lbfgs_rank,
+             20,
              "Rank of L-BFGS inverse Hessian approximation in line search.");
-DEFINE_bool(approximate_eigenvalue_bfgs_scaling, false,
+DEFINE_bool(approximate_eigenvalue_bfgs_scaling,
+            false,
             "Use approximate eigenvalue scaling in (L)BFGS line search.");
-DEFINE_double(sufficient_decrease, 1.0e-4,
+DEFINE_double(sufficient_decrease,
+              1.0e-4,
               "Line search Armijo sufficient (function) decrease factor.");
-DEFINE_double(sufficient_curvature_decrease, 0.9,
+DEFINE_double(sufficient_curvature_decrease,
+              0.9,
               "Line search Wolfe sufficient curvature decrease factor.");
 DEFINE_int32(num_iterations, 10000, "Number of iterations");
-DEFINE_bool(nonmonotonic_steps, false, "Trust region algorithm can use"
-            " nonmonotic steps");
+DEFINE_bool(nonmonotonic_steps,
+            false,
+            "Trust region algorithm can use nonmonotic steps");
 DEFINE_double(initial_trust_region_radius, 1e4, "Initial trust region radius");
-DEFINE_bool(use_numeric_diff, false,
+DEFINE_bool(use_numeric_diff,
+            false,
             "Use numeric differentiation instead of automatic "
             "differentiation.");
-DEFINE_string(numeric_diff_method, "ridders", "When using numeric "
-              "differentiation, selects algorithm. Options are: central, "
-              "forward, ridders.");
-DEFINE_double(ridders_step_size, 1e-9, "Initial step size for Ridders "
-              "numeric differentiation.");
-DEFINE_int32(ridders_extrapolations, 3, "Maximal number of Ridders "
-             "extrapolations.");
+DEFINE_string(numeric_diff_method,
+              "ridders",
+              "When using numeric differentiation, selects algorithm. Options "
+              "are: central, forward, ridders.");
+DEFINE_double(ridders_step_size,
+              1e-9,
+              "Initial step size for Ridders numeric differentiation.");
+DEFINE_int32(ridders_extrapolations,
+             3,
+             "Maximal number of Ridders extrapolations.");
 
 namespace ceres {
 namespace examples {
+namespace {
 
 using Eigen::Dynamic;
 using Eigen::RowMajor;
@@ -148,7 +167,7 @@
 void SplitStringUsingChar(const string& full,
                           const char delim,
                           vector<string>* result) {
-  std::back_insert_iterator< vector<string> > it(*result);
+  std::back_insert_iterator<vector<string>> it(*result);
 
   const char* p = full.data();
   const char* end = p + full.size();
@@ -221,12 +240,12 @@
 
     // Parse the remaining parameter lines.
     for (int parameter_id = 1; parameter_id < kNumParameters; ++parameter_id) {
-     GetAndSplitLine(ifs, &pieces);
-     // b2, b3, ....
-     for (int i = 0; i < kNumTries; ++i) {
-       initial_parameters_(i, parameter_id) = atof(pieces[i + 2].c_str());
-     }
-     final_parameters_(0, parameter_id) = atof(pieces[2 + kNumTries].c_str());
+      GetAndSplitLine(ifs, &pieces);
+      // b2, b3, ....
+      for (int i = 0; i < kNumTries; ++i) {
+        initial_parameters_(i, parameter_id) = atof(pieces[i + 2].c_str());
+      }
+      final_parameters_(0, parameter_id) = atof(pieces[2 + kNumTries].c_str());
     }
 
     // Certfied cost
@@ -240,26 +259,28 @@
       GetAndSplitLine(ifs, &pieces);
       // Response.
       for (int j = 0; j < kNumResponses; ++j) {
-        response_(i, j) =  atof(pieces[j].c_str());
+        response_(i, j) = atof(pieces[j].c_str());
       }
 
       // Predictor variables.
       for (int j = 0; j < kNumPredictors; ++j) {
-        predictor_(i, j) =  atof(pieces[j + kNumResponses].c_str());
+        predictor_(i, j) = atof(pieces[j + kNumResponses].c_str());
       }
     }
   }
 
-  Matrix initial_parameters(int start) const { return initial_parameters_.row(start); }  // NOLINT
-  Matrix final_parameters() const  { return final_parameters_; }
-  Matrix predictor()        const { return predictor_;         }
-  Matrix response()         const { return response_;          }
-  int predictor_size()      const { return predictor_.cols();  }
-  int num_observations()    const { return predictor_.rows();  }
-  int response_size()       const { return response_.cols();   }
-  int num_parameters()      const { return initial_parameters_.cols(); }
-  int num_starts()          const { return initial_parameters_.rows(); }
-  double certified_cost()   const { return certified_cost_; }
+  Matrix initial_parameters(int start) const {
+    return initial_parameters_.row(start);
+  }  // NOLINT
+  Matrix final_parameters() const { return final_parameters_; }
+  Matrix predictor() const { return predictor_; }
+  Matrix response() const { return response_; }
+  int predictor_size() const { return predictor_.cols(); }
+  int num_observations() const { return predictor_.rows(); }
+  int response_size() const { return response_.cols(); }
+  int num_parameters() const { return initial_parameters_.cols(); }
+  int num_starts() const { return initial_parameters_.rows(); }
+  double certified_cost() const { return certified_cost_; }
 
  private:
   Matrix predictor_;
@@ -269,21 +290,23 @@
   double certified_cost_;
 };
 
-#define NIST_BEGIN(CostFunctionName)                          \
-  struct CostFunctionName {                                   \
-  CostFunctionName(const double* const x,                     \
-                   const double* const y,                     \
-                   const int n)                               \
-      : x_(x), y_(y), n_(n) {}                                \
-    const double* x_;                                         \
-    const double* y_;                                         \
-    const int n_;                                             \
-    template <typename T>                                     \
-    bool operator()(const T* const b, T* residual) const {    \
-      for (int i = 0; i < n_; ++i) {                          \
-        const T x(x_[i]);                                     \
+#define NIST_BEGIN(CostFunctionName)                       \
+  struct CostFunctionName {                                \
+    CostFunctionName(const double* const x,                \
+                     const double* const y,                \
+                     const int n)                          \
+        : x_(x), y_(y), n_(n) {}                           \
+    const double* x_;                                      \
+    const double* y_;                                      \
+    const int n_;                                          \
+    template <typename T>                                  \
+    bool operator()(const T* const b, T* residual) const { \
+      for (int i = 0; i < n_; ++i) {                       \
+        const T x(x_[i]);                                  \
         residual[i] = y_[i] - (
 
+// clang-format off
+
 #define NIST_END ); } return true; }};
 
 // y = b1 * (b2+x)**(-1/b3)  +  e
@@ -429,6 +452,8 @@
   const int n_;
 };
 
+// clang-format on
+
 static void SetNumericDiffOptions(ceres::NumericDiffOptions* options) {
   options->max_num_ridders_extrapolations = FLAGS_ridders_extrapolations;
   options->ridders_relative_initial_step_size = FLAGS_ridders_step_size;
@@ -472,9 +497,9 @@
 
 string JoinPath(const string& dirname, const string& basename) {
 #ifdef _WIN32
-    static const char separator = '\\';
+  static const char separator = '\\';
 #else
-    static const char separator = '/';
+  static const char separator = '/';
 #endif  // _WIN32
 
   if ((!basename.empty() && basename[0] == separator) || dirname.empty()) {
@@ -490,8 +515,7 @@
 CostFunction* CreateCostFunction(const Matrix& predictor,
                                  const Matrix& response,
                                  const int num_observations) {
-  Model* model =
-      new Model(predictor.data(), response.data(), num_observations);
+  Model* model = new Model(predictor.data(), response.data(), num_observations);
   ceres::CostFunction* cost_function = NULL;
   if (FLAGS_use_numeric_diff) {
     ceres::NumericDiffOptions options;
@@ -501,28 +525,19 @@
                                                   ceres::CENTRAL,
                                                   ceres::DYNAMIC,
                                                   num_parameters>(
-          model,
-          ceres::TAKE_OWNERSHIP,
-          num_observations,
-          options);
+          model, ceres::TAKE_OWNERSHIP, num_observations, options);
     } else if (FLAGS_numeric_diff_method == "forward") {
       cost_function = new NumericDiffCostFunction<Model,
                                                   ceres::FORWARD,
                                                   ceres::DYNAMIC,
                                                   num_parameters>(
-          model,
-          ceres::TAKE_OWNERSHIP,
-          num_observations,
-          options);
+          model, ceres::TAKE_OWNERSHIP, num_observations, options);
     } else if (FLAGS_numeric_diff_method == "ridders") {
       cost_function = new NumericDiffCostFunction<Model,
                                                   ceres::RIDDERS,
                                                   ceres::DYNAMIC,
                                                   num_parameters>(
-          model,
-          ceres::TAKE_OWNERSHIP,
-          num_observations,
-          options);
+          model, ceres::TAKE_OWNERSHIP, num_observations, options);
     } else {
       LOG(ERROR) << "Invalid numeric diff method specified";
       return 0;
@@ -571,8 +586,9 @@
   int num_success = 0;
   for (int start = 0; start < nist_problem.num_starts(); ++start) {
     Matrix initial_parameters = nist_problem.initial_parameters(start);
-    ceres::CostFunction* cost_function = CreateCostFunction<Model, num_parameters>(
-        predictor, response,  nist_problem.num_observations());
+    ceres::CostFunction* cost_function =
+        CreateCostFunction<Model, num_parameters>(
+            predictor, response, nist_problem.num_observations());
 
     double initial_cost;
     double final_cost;
@@ -590,7 +606,7 @@
       ceres::TinySolverCostFunctionAdapter<Eigen::Dynamic, num_parameters> cfa(
           *cost_function);
       typedef ceres::TinySolver<
-          ceres::TinySolverCostFunctionAdapter<Eigen::Dynamic, num_parameters> >
+          ceres::TinySolverCostFunctionAdapter<Eigen::Dynamic, num_parameters>>
           Solver;
       Solver solver;
       solver.options.max_num_iterations = FLAGS_num_iterations;
@@ -608,8 +624,8 @@
       delete cost_function;
     }
 
-    const double log_relative_error = ComputeLRE(nist_problem.final_parameters(),
-                                                 initial_parameters);
+    const double log_relative_error =
+        ComputeLRE(nist_problem.final_parameters(), initial_parameters);
     const int kMinNumMatchingDigits = 4;
     if (log_relative_error > kMinNumMatchingDigits) {
       ++num_success;
@@ -628,7 +644,6 @@
   return num_success;
 }
 
-
 void SolveNISTProblems() {
   if (FLAGS_nist_data_dir.empty()) {
     LOG(FATAL) << "Must specify the directory containing the NIST problems";
@@ -678,11 +693,12 @@
        << "/54\n";
 }
 
+}  // namespace
 }  // namespace examples
 }  // namespace ceres
 
 int main(int argc, char** argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
   ceres::examples::SolveNISTProblems();
   return 0;
diff --git a/examples/pgm_image.h b/examples/pgm_image.h
index 1de8d67..3d2df63 100644
--- a/examples/pgm_image.h
+++ b/examples/pgm_image.h
@@ -46,7 +46,7 @@
 namespace ceres {
 namespace examples {
 
-template<typename Real>
+template <typename Real>
 class PGMImage {
  public:
   // Create an empty image
@@ -63,9 +63,9 @@
 
   // Get individual pixels
   Real* MutablePixel(int x, int y);
-  Real  Pixel(int x, int y) const;
+  Real Pixel(int x, int y) const;
   Real* MutablePixelFromLinearIndex(int index);
-  Real  PixelFromLinearIndex(int index) const;
+  Real PixelFromLinearIndex(int index) const;
   int LinearIndex(int x, int y) const;
 
   // Adds an image to another
@@ -90,52 +90,51 @@
 
 // --- IMPLEMENTATION
 
-template<typename Real>
+template <typename Real>
 PGMImage<Real>::PGMImage(int width, int height)
-  : height_(height), width_(width), data_(width*height, 0.0) {
-}
+    : height_(height), width_(width), data_(width * height, 0.0) {}
 
-template<typename Real>
+template <typename Real>
 PGMImage<Real>::PGMImage(std::string filename) {
   if (!ReadFromFile(filename)) {
     height_ = 0;
-    width_  = 0;
+    width_ = 0;
   }
 }
 
-template<typename Real>
+template <typename Real>
 void PGMImage<Real>::Set(double constant) {
   for (int i = 0; i < data_.size(); ++i) {
     data_[i] = constant;
   }
 }
 
-template<typename Real>
+template <typename Real>
 int PGMImage<Real>::width() const {
   return width_;
 }
 
-template<typename Real>
+template <typename Real>
 int PGMImage<Real>::height() const {
   return height_;
 }
 
-template<typename Real>
+template <typename Real>
 int PGMImage<Real>::NumPixels() const {
   return width_ * height_;
 }
 
-template<typename Real>
+template <typename Real>
 Real* PGMImage<Real>::MutablePixel(int x, int y) {
   return MutablePixelFromLinearIndex(LinearIndex(x, y));
 }
 
-template<typename Real>
+template <typename Real>
 Real PGMImage<Real>::Pixel(int x, int y) const {
   return PixelFromLinearIndex(LinearIndex(x, y));
 }
 
-template<typename Real>
+template <typename Real>
 Real* PGMImage<Real>::MutablePixelFromLinearIndex(int index) {
   CHECK(index >= 0);
   CHECK(index < width_ * height_);
@@ -143,22 +142,22 @@
   return &data_[index];
 }
 
-template<typename Real>
-Real  PGMImage<Real>::PixelFromLinearIndex(int index) const {
+template <typename Real>
+Real PGMImage<Real>::PixelFromLinearIndex(int index) const {
   CHECK(index >= 0);
   CHECK(index < width_ * height_);
   CHECK(index < data_.size());
   return data_[index];
 }
 
-template<typename Real>
+template <typename Real>
 int PGMImage<Real>::LinearIndex(int x, int y) const {
-  return x + width_*y;
+  return x + width_ * y;
 }
 
 // Adds an image to another
-template<typename Real>
-void PGMImage<Real>::operator+= (const PGMImage<Real>& image) {
+template <typename Real>
+void PGMImage<Real>::operator+=(const PGMImage<Real>& image) {
   CHECK(data_.size() == image.data_.size());
   for (int i = 0; i < data_.size(); ++i) {
     data_[i] += image.data_[i];
@@ -166,22 +165,22 @@
 }
 
 // Adds a constant to an image
-template<typename Real>
-void PGMImage<Real>::operator+= (Real a) {
+template <typename Real>
+void PGMImage<Real>::operator+=(Real a) {
   for (int i = 0; i < data_.size(); ++i) {
     data_[i] += a;
   }
 }
 
 // Multiplies an image by a constant
-template<typename Real>
-void PGMImage<Real>::operator*= (Real a) {
+template <typename Real>
+void PGMImage<Real>::operator*=(Real a) {
   for (int i = 0; i < data_.size(); ++i) {
     data_[i] *= a;
   }
 }
 
-template<typename Real>
+template <typename Real>
 bool PGMImage<Real>::WriteToFile(std::string filename) const {
   std::ofstream outputfile(filename.c_str());
   outputfile << "P2" << std::endl;
@@ -191,7 +190,7 @@
   outputfile << width_ << ' ' << height_ << " 255 " << std::endl;
 
   // Write data
-  int num_pixels = width_*height_;
+  int num_pixels = width_ * height_;
   for (int i = 0; i < num_pixels; ++i) {
     // Convert to integer by rounding when writing file
     outputfile << static_cast<int>(data_[i] + 0.5) << ' ';
@@ -200,10 +199,10 @@
   return bool(outputfile);  // Returns true/false
 }
 
-namespace  {
+namespace {
 
 // Helper function to read data from a text file, ignoring "#" comments.
-template<typename T>
+template <typename T>
 bool GetIgnoreComment(std::istream* in, T& t) {
   std::string word;
   bool ok;
@@ -229,7 +228,7 @@
 }
 }  // namespace
 
-template<typename Real>
+template <typename Real>
 bool PGMImage<Real>::ReadFromFile(std::string filename) {
   std::ifstream inputfile(filename.c_str());
 
@@ -242,9 +241,9 @@
 
   // Read the image header
   int two_fifty_five;
-  if (!GetIgnoreComment(&inputfile, width_)  ||
+  if (!GetIgnoreComment(&inputfile, width_) ||
       !GetIgnoreComment(&inputfile, height_) ||
-      !GetIgnoreComment(&inputfile, two_fifty_five) ) {
+      !GetIgnoreComment(&inputfile, two_fifty_five)) {
     return false;
   }
   // Assert that the number of grey levels is 255.
@@ -253,7 +252,7 @@
   }
 
   // Now read the data
-  int num_pixels = width_*height_;
+  int num_pixels = width_ * height_;
   data_.resize(num_pixels);
   if (ch2 == '2') {
     // Ascii file
@@ -297,7 +296,7 @@
   return true;
 }
 
-template<typename Real>
+template <typename Real>
 bool PGMImage<Real>::SetData(const std::vector<Real>& new_data) {
   // This function cannot change the dimensions
   if (new_data.size() != data_.size()) {
@@ -307,7 +306,7 @@
   return true;
 }
 
-template<typename Real>
+template <typename Real>
 const std::vector<Real>& PGMImage<Real>::data() const {
   return data_;
 }
@@ -315,5 +314,4 @@
 }  // namespace examples
 }  // namespace ceres
 
-
 #endif  // CERES_EXAMPLES_PGM_IMAGE_H_
diff --git a/examples/powell.cc b/examples/powell.cc
index 614c9c6..c75ad24 100644
--- a/examples/powell.cc
+++ b/examples/powell.cc
@@ -45,6 +45,7 @@
 // Vol 7(1), March 1981.
 
 #include <vector>
+
 #include "ceres/ceres.h"
 #include "gflags/gflags.h"
 #include "glog/logging.h"
@@ -52,13 +53,12 @@
 using ceres::AutoDiffCostFunction;
 using ceres::CostFunction;
 using ceres::Problem;
-using ceres::Solver;
 using ceres::Solve;
+using ceres::Solver;
 
 struct F1 {
-  template <typename T> bool operator()(const T* const x1,
-                                        const T* const x2,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x1, const T* const x2, T* residual) const {
     // f1 = x1 + 10 * x2;
     residual[0] = x1[0] + 10.0 * x2[0];
     return true;
@@ -66,9 +66,8 @@
 };
 
 struct F2 {
-  template <typename T> bool operator()(const T* const x3,
-                                        const T* const x4,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x3, const T* const x4, T* residual) const {
     // f2 = sqrt(5) (x3 - x4)
     residual[0] = sqrt(5.0) * (x3[0] - x4[0]);
     return true;
@@ -76,9 +75,8 @@
 };
 
 struct F3 {
-  template <typename T> bool operator()(const T* const x2,
-                                        const T* const x3,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x2, const T* const x3, T* residual) const {
     // f3 = (x2 - 2 x3)^2
     residual[0] = (x2[0] - 2.0 * x3[0]) * (x2[0] - 2.0 * x3[0]);
     return true;
@@ -86,47 +84,44 @@
 };
 
 struct F4 {
-  template <typename T> bool operator()(const T* const x1,
-                                        const T* const x4,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const x1, const T* const x4, T* residual) const {
     // f4 = sqrt(10) (x1 - x4)^2
     residual[0] = sqrt(10.0) * (x1[0] - x4[0]) * (x1[0] - x4[0]);
     return true;
   }
 };
 
-DEFINE_string(minimizer, "trust_region",
+DEFINE_string(minimizer,
+              "trust_region",
               "Minimizer type to use, choices are: line_search & trust_region");
 
 int main(int argc, char** argv) {
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   google::InitGoogleLogging(argv[0]);
 
-  double x1 =  3.0;
+  double x1 = 3.0;
   double x2 = -1.0;
-  double x3 =  0.0;
-  double x4 =  1.0;
+  double x3 = 0.0;
+  double x4 = 1.0;
 
   Problem problem;
   // Add residual terms to the problem using the using the autodiff
   // wrapper to get the derivatives automatically. The parameters, x1 through
   // x4, are modified in place.
-  problem.AddResidualBlock(new AutoDiffCostFunction<F1, 1, 1, 1>(new F1),
-                           NULL,
-                           &x1, &x2);
-  problem.AddResidualBlock(new AutoDiffCostFunction<F2, 1, 1, 1>(new F2),
-                           NULL,
-                           &x3, &x4);
-  problem.AddResidualBlock(new AutoDiffCostFunction<F3, 1, 1, 1>(new F3),
-                           NULL,
-                           &x2, &x3);
-  problem.AddResidualBlock(new AutoDiffCostFunction<F4, 1, 1, 1>(new F4),
-                           NULL,
-                           &x1, &x4);
+  problem.AddResidualBlock(
+      new AutoDiffCostFunction<F1, 1, 1, 1>(new F1), NULL, &x1, &x2);
+  problem.AddResidualBlock(
+      new AutoDiffCostFunction<F2, 1, 1, 1>(new F2), NULL, &x3, &x4);
+  problem.AddResidualBlock(
+      new AutoDiffCostFunction<F3, 1, 1, 1>(new F3), NULL, &x2, &x3);
+  problem.AddResidualBlock(
+      new AutoDiffCostFunction<F4, 1, 1, 1>(new F4), NULL, &x1, &x4);
 
   Solver::Options options;
-  LOG_IF(FATAL, !ceres::StringToMinimizerType(FLAGS_minimizer,
-                                              &options.minimizer_type))
+  LOG_IF(
+      FATAL,
+      !ceres::StringToMinimizerType(FLAGS_minimizer, &options.minimizer_type))
       << "Invalid minimizer: " << FLAGS_minimizer
       << ", valid options are: trust_region and line_search.";
 
@@ -134,21 +129,25 @@
   options.linear_solver_type = ceres::DENSE_QR;
   options.minimizer_progress_to_stdout = true;
 
+  // clang-format off
   std::cout << "Initial x1 = " << x1
             << ", x2 = " << x2
             << ", x3 = " << x3
             << ", x4 = " << x4
             << "\n";
+  // clang-format on
 
   // Run the solver!
   Solver::Summary summary;
   Solve(options, &problem, &summary);
 
   std::cout << summary.FullReport() << "\n";
+  // clang-format off
   std::cout << "Final x1 = " << x1
             << ", x2 = " << x2
             << ", x3 = " << x3
             << ", x4 = " << x4
             << "\n";
+  // clang-format on
   return 0;
 }
diff --git a/examples/random.h b/examples/random.h
index 7b09b15..ace0711 100644
--- a/examples/random.h
+++ b/examples/random.h
@@ -52,7 +52,7 @@
     x1 = 2.0 * RandDouble() - 1.0;
     x2 = 2.0 * RandDouble() - 1.0;
     w = x1 * x1 + x2 * x2;
-  } while ( w >= 1.0 || w == 0.0 );
+  } while (w >= 1.0 || w == 0.0);
 
   w = sqrt((-2.0 * log(w)) / w);
   return x1 * w;
diff --git a/examples/robot_pose_mle.cc b/examples/robot_pose_mle.cc
index 1f5058a..ab9a098 100644
--- a/examples/robot_pose_mle.cc
+++ b/examples/robot_pose_mle.cc
@@ -125,8 +125,9 @@
 // will be computed by a DynamicAutoDiffCostFunction since the number of
 // odoemtry observations will only be known at run time.
 
-#include <cstdio>
 #include <math.h>
+
+#include <cstdio>
 #include <vector>
 
 #include "ceres/ceres.h"
@@ -136,9 +137,9 @@
 #include "random.h"
 
 using ceres::AutoDiffCostFunction;
-using ceres::DynamicAutoDiffCostFunction;
 using ceres::CauchyLoss;
 using ceres::CostFunction;
+using ceres::DynamicAutoDiffCostFunction;
 using ceres::LossFunction;
 using ceres::Problem;
 using ceres::Solve;
@@ -147,26 +148,31 @@
 using std::min;
 using std::vector;
 
-DEFINE_double(corridor_length, 30.0, "Length of the corridor that the robot is "
-              "travelling down.");
+DEFINE_double(corridor_length,
+              30.0,
+              "Length of the corridor that the robot is travelling down.");
 
-DEFINE_double(pose_separation, 0.5, "The distance that the robot traverses "
-              "between successive odometry updates.");
+DEFINE_double(pose_separation,
+              0.5,
+              "The distance that the robot traverses between successive "
+              "odometry updates.");
 
-DEFINE_double(odometry_stddev, 0.1, "The standard deviation of "
-              "odometry error of the robot.");
+DEFINE_double(odometry_stddev,
+              0.1,
+              "The standard deviation of odometry error of the robot.");
 
-DEFINE_double(range_stddev, 0.01, "The standard deviation of range readings of "
-              "the robot.");
+DEFINE_double(range_stddev,
+              0.01,
+              "The standard deviation of range readings of the robot.");
 
 // The stride length of the dynamic_autodiff_cost_function evaluator.
-static const int kStride = 10;
+static constexpr int kStride = 10;
 
 struct OdometryConstraint {
   typedef AutoDiffCostFunction<OdometryConstraint, 1, 1> OdometryCostFunction;
 
-  OdometryConstraint(double odometry_mean, double odometry_stddev) :
-      odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {}
+  OdometryConstraint(double odometry_mean, double odometry_stddev)
+      : odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {}
 
   template <typename T>
   bool operator()(const T* const odometry, T* residual) const {
@@ -187,13 +193,14 @@
   typedef DynamicAutoDiffCostFunction<RangeConstraint, kStride>
       RangeCostFunction;
 
-  RangeConstraint(
-      int pose_index,
-      double range_reading,
-      double range_stddev,
-      double corridor_length) :
-      pose_index(pose_index), range_reading(range_reading),
-      range_stddev(range_stddev), corridor_length(corridor_length) {}
+  RangeConstraint(int pose_index,
+                  double range_reading,
+                  double range_stddev,
+                  double corridor_length)
+      : pose_index(pose_index),
+        range_reading(range_reading),
+        range_stddev(range_stddev),
+        corridor_length(corridor_length) {}
 
   template <typename T>
   bool operator()(T const* const* relative_poses, T* residuals) const {
@@ -201,8 +208,8 @@
     for (int i = 0; i <= pose_index; ++i) {
       global_pose += relative_poses[i][0];
     }
-    residuals[0] = (global_pose + range_reading - corridor_length) /
-        range_stddev;
+    residuals[0] =
+        (global_pose + range_reading - corridor_length) / range_stddev;
     return true;
   }
 
@@ -231,16 +238,18 @@
   const double corridor_length;
 };
 
+namespace {
+
 void SimulateRobot(vector<double>* odometry_values,
                    vector<double>* range_readings) {
-  const int num_steps = static_cast<int>(
-      ceil(FLAGS_corridor_length / FLAGS_pose_separation));
+  const int num_steps =
+      static_cast<int>(ceil(FLAGS_corridor_length / FLAGS_pose_separation));
 
   // The robot starts out at the origin.
   double robot_location = 0.0;
   for (int i = 0; i < num_steps; ++i) {
-    const double actual_odometry_value = min(
-        FLAGS_pose_separation, FLAGS_corridor_length - robot_location);
+    const double actual_odometry_value =
+        min(FLAGS_pose_separation, FLAGS_corridor_length - robot_location);
     robot_location += actual_odometry_value;
     const double actual_range = FLAGS_corridor_length - robot_location;
     const double observed_odometry =
@@ -261,17 +270,22 @@
     robot_location += odometry_readings[i];
     const double range_error =
         robot_location + range_readings[i] - FLAGS_corridor_length;
-    const double odometry_error =
-        FLAGS_pose_separation - odometry_readings[i];
+    const double odometry_error = FLAGS_pose_separation - odometry_readings[i];
     printf("%4d: %8.3f %8.3f %8.3f %8.3f %8.3f\n",
-           static_cast<int>(i), robot_location, odometry_readings[i],
-           range_readings[i], range_error, odometry_error);
+           static_cast<int>(i),
+           robot_location,
+           odometry_readings[i],
+           range_readings[i],
+           range_error,
+           odometry_error);
   }
 }
 
+}  // namespace
+
 int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
   // Make sure that the arguments parsed are all positive.
   CHECK_GT(FLAGS_corridor_length, 0.0);
   CHECK_GT(FLAGS_pose_separation, 0.0);
diff --git a/examples/robust_curve_fitting.cc b/examples/robust_curve_fitting.cc
index 6186aa1..9b526c5 100644
--- a/examples/robust_curve_fitting.cc
+++ b/examples/robust_curve_fitting.cc
@@ -43,6 +43,7 @@
 //   data = [x', y_observed'];
 
 const int kNumObservations = 67;
+// clang-format off
 const double data[] = {
 0.000000e+00, 1.133898e+00,
 7.500000e-02, 1.334902e+00,
@@ -112,21 +113,20 @@
 4.875000e+00, 4.727863e+00,
 4.950000e+00, 4.669206e+00
 };
+// clang-format on
 
 using ceres::AutoDiffCostFunction;
-using ceres::CostFunction;
 using ceres::CauchyLoss;
+using ceres::CostFunction;
 using ceres::Problem;
 using ceres::Solve;
 using ceres::Solver;
 
 struct ExponentialResidual {
-  ExponentialResidual(double x, double y)
-      : x_(x), y_(y) {}
+  ExponentialResidual(double x, double y) : x_(x), y_(y) {}
 
-  template <typename T> bool operator()(const T* const m,
-                                        const T* const c,
-                                        T* residual) const {
+  template <typename T>
+  bool operator()(const T* const m, const T* const c, T* residual) const {
     residual[0] = y_ - exp(m[0] * x_ + c[0]);
     return true;
   }
@@ -147,9 +147,7 @@
     CostFunction* cost_function =
         new AutoDiffCostFunction<ExponentialResidual, 1, 1, 1>(
             new ExponentialResidual(data[2 * i], data[2 * i + 1]));
-    problem.AddResidualBlock(cost_function,
-                             new CauchyLoss(0.5),
-                             &m, &c);
+    problem.AddResidualBlock(cost_function, new CauchyLoss(0.5), &m, &c);
   }
 
   Solver::Options options;
diff --git a/examples/rosenbrock.cc b/examples/rosenbrock.cc
index 3f64f1c..1b9aef6 100644
--- a/examples/rosenbrock.cc
+++ b/examples/rosenbrock.cc
@@ -53,7 +53,6 @@
   virtual int NumParameters() const { return 2; }
 };
 
-
 int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);
 
@@ -68,7 +67,7 @@
 
   std::cout << summary.FullReport() << "\n";
   std::cout << "Initial x: " << -1.2 << " y: " << 1.0 << "\n";
-  std::cout << "Final   x: " << parameters[0]
-            << " y: " << parameters[1] << "\n";
+  std::cout << "Final   x: " << parameters[0] << " y: " << parameters[1]
+            << "\n";
   return 0;
 }
diff --git a/examples/sampled_function/CMakeLists.txt b/examples/sampled_function/CMakeLists.txt
index 57f31d1..8a17cad 100644
--- a/examples/sampled_function/CMakeLists.txt
+++ b/examples/sampled_function/CMakeLists.txt
@@ -29,4 +29,4 @@
 # Author: vitus@google.com (Michael Vitus)
 
 add_executable(sampled_function sampled_function.cc)
-target_link_libraries(sampled_function ceres)
+target_link_libraries(sampled_function Ceres::ceres)
diff --git a/examples/sampled_function/README.md b/examples/sampled_function/README.md
index 77ce365..ef1af43 100644
--- a/examples/sampled_function/README.md
+++ b/examples/sampled_function/README.md
@@ -15,7 +15,7 @@
 interpolation method requires knowledge of the function derivatives at the
 control points, however we only know the function values. Consequently, we will
 use the data to estimate derivatives at the control points. The choice of how to
-compute the derivatives is not unique and Ceres uses the Catmull–Rom Spline
+compute the derivatives is not unique and Ceres uses the Catmull-Rom Spline
 variant which uses `0.5 * (p_{k+1} - p_{k-1})` as the derivative for control
 point `p_k.` This produces a first order differentiable interpolating
 function. The two dimensional interpolation scheme is a generalization of the
diff --git a/examples/sampled_function/sampled_function.cc b/examples/sampled_function/sampled_function.cc
index 093276a..e96018d 100644
--- a/examples/sampled_function/sampled_function.cc
+++ b/examples/sampled_function/sampled_function.cc
@@ -35,35 +35,35 @@
 #include "ceres/cubic_interpolation.h"
 #include "glog/logging.h"
 
-using ceres::Grid1D;
-using ceres::CubicInterpolator;
 using ceres::AutoDiffCostFunction;
 using ceres::CostFunction;
+using ceres::CubicInterpolator;
+using ceres::Grid1D;
 using ceres::Problem;
-using ceres::Solver;
 using ceres::Solve;
+using ceres::Solver;
 
 // A simple cost functor that interfaces an interpolated table of
 // values with automatic differentiation.
 struct InterpolatedCostFunctor {
   explicit InterpolatedCostFunctor(
-      const CubicInterpolator<Grid1D<double> >& interpolator)
-      : interpolator_(interpolator) {
-  }
+      const CubicInterpolator<Grid1D<double>>& interpolator)
+      : interpolator_(interpolator) {}
 
-  template<typename T> bool operator()(const T* x, T* residuals) const {
+  template <typename T>
+  bool operator()(const T* x, T* residuals) const {
     interpolator_.Evaluate(*x, residuals);
     return true;
   }
 
   static CostFunction* Create(
-      const CubicInterpolator<Grid1D<double> >& interpolator) {
+      const CubicInterpolator<Grid1D<double>>& interpolator) {
     return new AutoDiffCostFunction<InterpolatedCostFunctor, 1, 1>(
         new InterpolatedCostFunctor(interpolator));
   }
 
  private:
-  const CubicInterpolator<Grid1D<double> >& interpolator_;
+  const CubicInterpolator<Grid1D<double>>& interpolator_;
 };
 
 int main(int argc, char** argv) {
@@ -77,7 +77,7 @@
   }
 
   Grid1D<double> array(values, 0, kNumSamples);
-  CubicInterpolator<Grid1D<double> > interpolator(array);
+  CubicInterpolator<Grid1D<double>> interpolator(array);
 
   double x = 1.0;
   Problem problem;
diff --git a/examples/simple_bundle_adjuster.cc b/examples/simple_bundle_adjuster.cc
index dec6cd6..8180d73 100644
--- a/examples/simple_bundle_adjuster.cc
+++ b/examples/simple_bundle_adjuster.cc
@@ -52,10 +52,10 @@
     delete[] parameters_;
   }
 
-  int num_observations()       const { return num_observations_;               }
-  const double* observations() const { return observations_;                   }
-  double* mutable_cameras()          { return parameters_;                     }
-  double* mutable_points()           { return parameters_  + 9 * num_cameras_; }
+  int num_observations() const { return num_observations_; }
+  const double* observations() const { return observations_; }
+  double* mutable_cameras() { return parameters_; }
+  double* mutable_points() { return parameters_ + 9 * num_cameras_; }
 
   double* mutable_camera_for_observation(int i) {
     return mutable_cameras() + camera_index_[i] * 9;
@@ -85,7 +85,7 @@
       FscanfOrDie(fptr, "%d", camera_index_ + i);
       FscanfOrDie(fptr, "%d", point_index_ + i);
       for (int j = 0; j < 2; ++j) {
-        FscanfOrDie(fptr, "%lf", observations_ + 2*i + j);
+        FscanfOrDie(fptr, "%lf", observations_ + 2 * i + j);
       }
     }
 
@@ -96,8 +96,8 @@
   }
 
  private:
-  template<typename T>
-  void FscanfOrDie(FILE *fptr, const char *format, T *value) {
+  template <typename T>
+  void FscanfOrDie(FILE* fptr, const char* format, T* value) {
     int num_scanned = fscanf(fptr, format, value);
     if (num_scanned != 1) {
       LOG(FATAL) << "Invalid UW data file.";
@@ -139,14 +139,14 @@
     // Compute the center of distortion. The sign change comes from
     // the camera model that Noah Snavely's Bundler assumes, whereby
     // the camera coordinate system has a negative z axis.
-    T xp = - p[0] / p[2];
-    T yp = - p[1] / p[2];
+    T xp = -p[0] / p[2];
+    T yp = -p[1] / p[2];
 
     // Apply second and fourth order radial distortion.
     const T& l1 = camera[7];
     const T& l2 = camera[8];
-    T r2 = xp*xp + yp*yp;
-    T distortion = 1.0 + r2  * (l1 + l2  * r2);
+    T r2 = xp * xp + yp * yp;
+    T distortion = 1.0 + r2 * (l1 + l2 * r2);
 
     // Compute final projected point position.
     const T& focal = camera[6];
@@ -165,7 +165,7 @@
   static ceres::CostFunction* Create(const double observed_x,
                                      const double observed_y) {
     return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>(
-                new SnavelyReprojectionError(observed_x, observed_y)));
+        new SnavelyReprojectionError(observed_x, observed_y)));
   }
 
   double observed_x;
@@ -195,9 +195,8 @@
     // dimensional residual. Internally, the cost function stores the observed
     // image location and compares the reprojection against the observation.
 
-    ceres::CostFunction* cost_function =
-        SnavelyReprojectionError::Create(observations[2 * i + 0],
-                                         observations[2 * i + 1]);
+    ceres::CostFunction* cost_function = SnavelyReprojectionError::Create(
+        observations[2 * i + 0], observations[2 * i + 1]);
     problem.AddResidualBlock(cost_function,
                              NULL /* squared loss */,
                              bal_problem.mutable_camera_for_observation(i),
diff --git a/examples/slam/common/read_g2o.h b/examples/slam/common/read_g2o.h
index 71b071c..fea32e9 100644
--- a/examples/slam/common/read_g2o.h
+++ b/examples/slam/common/read_g2o.h
@@ -97,7 +97,9 @@
 // where I_ij is the (i, j)-th entry of the information matrix for the
 // measurement. Only the upper-triangular part is stored. The measurement order
 // is the delta position followed by the delta orientation.
-template <typename Pose, typename Constraint, typename MapAllocator,
+template <typename Pose,
+          typename Constraint,
+          typename MapAllocator,
           typename VectorAllocator>
 bool ReadG2oFile(const std::string& filename,
                  std::map<int, Pose, std::less<int>, MapAllocator>* poses,
diff --git a/examples/slam/pose_graph_2d/CMakeLists.txt b/examples/slam/pose_graph_2d/CMakeLists.txt
index d654e8c..20af056 100644
--- a/examples/slam/pose_graph_2d/CMakeLists.txt
+++ b/examples/slam/pose_graph_2d/CMakeLists.txt
@@ -35,5 +35,5 @@
     pose_graph_2d.cc
     pose_graph_2d_error_term.h
     types.h)
-  target_link_libraries(pose_graph_2d ceres ${GFLAGS_LIBRARIES})
-endif (GFLAGS)
\ No newline at end of file
+  target_link_libraries(pose_graph_2d Ceres::ceres gflags)
+endif (GFLAGS)
diff --git a/examples/slam/pose_graph_2d/angle_local_parameterization.h b/examples/slam/pose_graph_2d/angle_local_parameterization.h
index 428cccc..a81637c 100644
--- a/examples/slam/pose_graph_2d/angle_local_parameterization.h
+++ b/examples/slam/pose_graph_2d/angle_local_parameterization.h
@@ -41,9 +41,9 @@
 // [-pi to pi).
 class AngleLocalParameterization {
  public:
-
   template <typename T>
-  bool operator()(const T* theta_radians, const T* delta_theta_radians,
+  bool operator()(const T* theta_radians,
+                  const T* delta_theta_radians,
                   T* theta_radians_plus_delta) const {
     *theta_radians_plus_delta =
         NormalizeAngle(*theta_radians + *delta_theta_radians);
@@ -53,7 +53,8 @@
 
   static ceres::LocalParameterization* Create() {
     return (new ceres::AutoDiffLocalParameterization<AngleLocalParameterization,
-                                                     1, 1>);
+                                                     1,
+                                                     1>);
   }
 };
 
diff --git a/examples/slam/pose_graph_2d/normalize_angle.h b/examples/slam/pose_graph_2d/normalize_angle.h
index afd5df4..c215671 100644
--- a/examples/slam/pose_graph_2d/normalize_angle.h
+++ b/examples/slam/pose_graph_2d/normalize_angle.h
@@ -44,7 +44,7 @@
   // Use ceres::floor because it is specialized for double and Jet types.
   T two_pi(2.0 * M_PI);
   return angle_radians -
-      two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi);
+         two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi);
 }
 
 }  // namespace examples
diff --git a/examples/slam/pose_graph_2d/pose_graph_2d.cc b/examples/slam/pose_graph_2d/pose_graph_2d.cc
index b9374db..1172123 100644
--- a/examples/slam/pose_graph_2d/pose_graph_2d.cc
+++ b/examples/slam/pose_graph_2d/pose_graph_2d.cc
@@ -51,6 +51,7 @@
 
 namespace ceres {
 namespace examples {
+namespace {
 
 // Constructs the nonlinear least squares optimization problem from the pose
 // graph constraints.
@@ -70,7 +71,8 @@
 
   for (std::vector<Constraint2d>::const_iterator constraints_iter =
            constraints.begin();
-       constraints_iter != constraints.end(); ++constraints_iter) {
+       constraints_iter != constraints.end();
+       ++constraints_iter) {
     const Constraint2d& constraint = *constraints_iter;
 
     std::map<int, Pose2d>::iterator pose_begin_iter =
@@ -87,16 +89,19 @@
     // Ceres will take ownership of the pointer.
     ceres::CostFunction* cost_function = PoseGraph2dErrorTerm::Create(
         constraint.x, constraint.y, constraint.yaw_radians, sqrt_information);
-    problem->AddResidualBlock(
-        cost_function, loss_function, &pose_begin_iter->second.x,
-        &pose_begin_iter->second.y, &pose_begin_iter->second.yaw_radians,
-        &pose_end_iter->second.x, &pose_end_iter->second.y,
-        &pose_end_iter->second.yaw_radians);
+    problem->AddResidualBlock(cost_function,
+                              loss_function,
+                              &pose_begin_iter->second.x,
+                              &pose_begin_iter->second.y,
+                              &pose_begin_iter->second.yaw_radians,
+                              &pose_end_iter->second.x,
+                              &pose_end_iter->second.y,
+                              &pose_end_iter->second.yaw_radians);
 
     problem->SetParameterization(&pose_begin_iter->second.yaw_radians,
-                                angle_local_parameterization);
+                                 angle_local_parameterization);
     problem->SetParameterization(&pose_end_iter->second.yaw_radians,
-                                angle_local_parameterization);
+                                 angle_local_parameterization);
   }
 
   // The pose graph optimization problem has three DOFs that are not fully
@@ -106,8 +111,7 @@
   // internal damping which mitigate this issue, but it is better to properly
   // constrain the gauge freedom. This can be done by setting one of the poses
   // as constant so the optimizer cannot change it.
-  std::map<int, Pose2d>::iterator pose_start_iter =
-      poses->begin();
+  std::map<int, Pose2d>::iterator pose_start_iter = poses->begin();
   CHECK(pose_start_iter != poses->end()) << "There are no poses.";
   problem->SetParameterBlockConstant(&pose_start_iter->second.x);
   problem->SetParameterBlockConstant(&pose_start_iter->second.y);
@@ -140,20 +144,22 @@
     return false;
   }
   for (std::map<int, Pose2d>::const_iterator poses_iter = poses.begin();
-       poses_iter != poses.end(); ++poses_iter) {
+       poses_iter != poses.end();
+       ++poses_iter) {
     const std::map<int, Pose2d>::value_type& pair = *poses_iter;
-    outfile <<  pair.first << " " << pair.second.x << " " << pair.second.y
-            << ' ' << pair.second.yaw_radians << '\n';
+    outfile << pair.first << " " << pair.second.x << " " << pair.second.y << ' '
+            << pair.second.yaw_radians << '\n';
   }
   return true;
 }
 
+}  // namespace
 }  // namespace examples
 }  // namespace ceres
 
 int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
 
   CHECK(FLAGS_input != "") << "Need to specify the filename to read.";
 
diff --git a/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h b/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h
index 20656d2..2df31f6 100644
--- a/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h
+++ b/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h
@@ -59,24 +59,29 @@
 // [-pi, pi).
 class PoseGraph2dErrorTerm {
  public:
-  PoseGraph2dErrorTerm(double x_ab, double y_ab, double yaw_ab_radians,
+  PoseGraph2dErrorTerm(double x_ab,
+                       double y_ab,
+                       double yaw_ab_radians,
                        const Eigen::Matrix3d& sqrt_information)
       : p_ab_(x_ab, y_ab),
         yaw_ab_radians_(yaw_ab_radians),
         sqrt_information_(sqrt_information) {}
 
   template <typename T>
-  bool operator()(const T* const x_a, const T* const y_a, const T* const yaw_a,
-                  const T* const x_b, const T* const y_b, const T* const yaw_b,
+  bool operator()(const T* const x_a,
+                  const T* const y_a,
+                  const T* const yaw_a,
+                  const T* const x_b,
+                  const T* const y_b,
+                  const T* const yaw_b,
                   T* residuals_ptr) const {
     const Eigen::Matrix<T, 2, 1> p_a(*x_a, *y_a);
     const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b);
 
-    Eigen::Map<Eigen::Matrix<T, 3, 1> > residuals_map(residuals_ptr);
+    Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals_ptr);
 
     residuals_map.template head<2>() =
-        RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) -
-        p_ab_.cast<T>();
+        RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - p_ab_.cast<T>();
     residuals_map(2) = ceres::examples::NormalizeAngle(
         (*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_));
 
@@ -87,12 +92,14 @@
     return true;
   }
 
-  static ceres::CostFunction* Create(double x_ab, double y_ab,
+  static ceres::CostFunction* Create(double x_ab,
+                                     double y_ab,
                                      double yaw_ab_radians,
                                      const Eigen::Matrix3d& sqrt_information) {
-    return (new ceres::AutoDiffCostFunction<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1,
-                                            1, 1>(new PoseGraph2dErrorTerm(
-        x_ab, y_ab, yaw_ab_radians, sqrt_information)));
+    return (new ceres::
+                AutoDiffCostFunction<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1, 1, 1>(
+                    new PoseGraph2dErrorTerm(
+                        x_ab, y_ab, yaw_ab_radians, sqrt_information)));
   }
 
   EIGEN_MAKE_ALIGNED_OPERATOR_NEW
diff --git a/examples/slam/pose_graph_2d/types.h b/examples/slam/pose_graph_2d/types.h
index a54d9bf..3c13824 100644
--- a/examples/slam/pose_graph_2d/types.h
+++ b/examples/slam/pose_graph_2d/types.h
@@ -50,12 +50,10 @@
   double yaw_radians;
 
   // The name of the data type in the g2o file format.
-  static std::string name() {
-    return "VERTEX_SE2";
-  }
+  static std::string name() { return "VERTEX_SE2"; }
 };
 
-std::istream& operator>>(std::istream& input, Pose2d& pose) {
+inline std::istream& operator>>(std::istream& input, Pose2d& pose) {
   input >> pose.x >> pose.y >> pose.yaw_radians;
   // Normalize the angle between -pi to pi.
   pose.yaw_radians = NormalizeAngle(pose.yaw_radians);
@@ -77,17 +75,15 @@
   Eigen::Matrix3d information;
 
   // The name of the data type in the g2o file format.
-  static std::string name() {
-    return "EDGE_SE2";
-  }
+  static std::string name() { return "EDGE_SE2"; }
 };
 
-std::istream& operator>>(std::istream& input, Constraint2d& constraint) {
+inline std::istream& operator>>(std::istream& input, Constraint2d& constraint) {
   input >> constraint.id_begin >> constraint.id_end >> constraint.x >>
-      constraint.y >> constraint.yaw_radians >>
-      constraint.information(0, 0) >> constraint.information(0, 1) >>
-      constraint.information(0, 2) >> constraint.information(1, 1) >>
-      constraint.information(1, 2) >> constraint.information(2, 2);
+      constraint.y >> constraint.yaw_radians >> constraint.information(0, 0) >>
+      constraint.information(0, 1) >> constraint.information(0, 2) >>
+      constraint.information(1, 1) >> constraint.information(1, 2) >>
+      constraint.information(2, 2);
 
   // Set the lower triangular part of the information matrix.
   constraint.information(1, 0) = constraint.information(0, 1);
diff --git a/examples/slam/pose_graph_3d/CMakeLists.txt b/examples/slam/pose_graph_3d/CMakeLists.txt
index 2c5fdc3..b6421cc 100644
--- a/examples/slam/pose_graph_3d/CMakeLists.txt
+++ b/examples/slam/pose_graph_3d/CMakeLists.txt
@@ -30,5 +30,5 @@
 
 if (GFLAGS)
   add_executable(pose_graph_3d pose_graph_3d.cc)
-  target_link_libraries(pose_graph_3d ceres ${GFLAGS_LIBRARIES})
-endif (GFLAGS)
\ No newline at end of file
+  target_link_libraries(pose_graph_3d Ceres::ceres gflags)
+endif (GFLAGS)
diff --git a/examples/slam/pose_graph_3d/pose_graph_3d.cc b/examples/slam/pose_graph_3d/pose_graph_3d.cc
index dcc85af..2f8d6a4 100644
--- a/examples/slam/pose_graph_3d/pose_graph_3d.cc
+++ b/examples/slam/pose_graph_3d/pose_graph_3d.cc
@@ -28,8 +28,8 @@
 //
 // Author: vitus@google.com (Michael Vitus)
 
-#include <iostream>
 #include <fstream>
+#include <iostream>
 #include <string>
 
 #include "ceres/ceres.h"
@@ -43,11 +43,13 @@
 
 namespace ceres {
 namespace examples {
+namespace {
 
 // Constructs the nonlinear least squares optimization problem from the pose
 // graph constraints.
 void BuildOptimizationProblem(const VectorOfConstraints& constraints,
-                              MapOfPoses* poses, ceres::Problem* problem) {
+                              MapOfPoses* poses,
+                              ceres::Problem* problem) {
   CHECK(poses != NULL);
   CHECK(problem != NULL);
   if (constraints.empty()) {
@@ -61,7 +63,8 @@
 
   for (VectorOfConstraints::const_iterator constraints_iter =
            constraints.begin();
-       constraints_iter != constraints.end(); ++constraints_iter) {
+       constraints_iter != constraints.end();
+       ++constraints_iter) {
     const Constraint3d& constraint = *constraints_iter;
 
     MapOfPoses::iterator pose_begin_iter = poses->find(constraint.id_begin);
@@ -77,7 +80,8 @@
     ceres::CostFunction* cost_function =
         PoseGraph3dErrorTerm::Create(constraint.t_be, sqrt_information);
 
-    problem->AddResidualBlock(cost_function, loss_function,
+    problem->AddResidualBlock(cost_function,
+                              loss_function,
                               pose_begin_iter->second.p.data(),
                               pose_begin_iter->second.q.coeffs().data(),
                               pose_end_iter->second.p.data(),
@@ -126,12 +130,17 @@
     LOG(ERROR) << "Error opening the file: " << filename;
     return false;
   }
-  for (std::map<int, Pose3d, std::less<int>,
-                Eigen::aligned_allocator<std::pair<const int, Pose3d> > >::
+  for (std::map<int,
+                Pose3d,
+                std::less<int>,
+                Eigen::aligned_allocator<std::pair<const int, Pose3d>>>::
            const_iterator poses_iter = poses.begin();
-       poses_iter != poses.end(); ++poses_iter) {
-    const std::map<int, Pose3d, std::less<int>,
-                   Eigen::aligned_allocator<std::pair<const int, Pose3d> > >::
+       poses_iter != poses.end();
+       ++poses_iter) {
+    const std::map<int,
+                   Pose3d,
+                   std::less<int>,
+                   Eigen::aligned_allocator<std::pair<const int, Pose3d>>>::
         value_type& pair = *poses_iter;
     outfile << pair.first << " " << pair.second.p.transpose() << " "
             << pair.second.q.x() << " " << pair.second.q.y() << " "
@@ -140,12 +149,13 @@
   return true;
 }
 
+}  // namespace
 }  // namespace examples
 }  // namespace ceres
 
 int main(int argc, char** argv) {
   google::InitGoogleLogging(argv[0]);
-  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+  GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
 
   CHECK(FLAGS_input != "") << "Need to specify the filename to read.";
 
diff --git a/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h b/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h
index aca819e..1f3e8de 100644
--- a/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h
+++ b/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h
@@ -33,7 +33,6 @@
 
 #include "Eigen/Core"
 #include "ceres/autodiff_cost_function.h"
-
 #include "types.h"
 
 namespace ceres {
@@ -75,14 +74,16 @@
       : t_ab_measured_(t_ab_measured), sqrt_information_(sqrt_information) {}
 
   template <typename T>
-  bool operator()(const T* const p_a_ptr, const T* const q_a_ptr,
-                  const T* const p_b_ptr, const T* const q_b_ptr,
+  bool operator()(const T* const p_a_ptr,
+                  const T* const q_a_ptr,
+                  const T* const p_b_ptr,
+                  const T* const q_b_ptr,
                   T* residuals_ptr) const {
-    Eigen::Map<const Eigen::Matrix<T, 3, 1> > p_a(p_a_ptr);
-    Eigen::Map<const Eigen::Quaternion<T> > q_a(q_a_ptr);
+    Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_a(p_a_ptr);
+    Eigen::Map<const Eigen::Quaternion<T>> q_a(q_a_ptr);
 
-    Eigen::Map<const Eigen::Matrix<T, 3, 1> > p_b(p_b_ptr);
-    Eigen::Map<const Eigen::Quaternion<T> > q_b(q_b_ptr);
+    Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_b(p_b_ptr);
+    Eigen::Map<const Eigen::Quaternion<T>> q_b(q_b_ptr);
 
     // Compute the relative transformation between the two frames.
     Eigen::Quaternion<T> q_a_inverse = q_a.conjugate();
@@ -98,7 +99,7 @@
     // Compute the residuals.
     // [ position         ]   [ delta_p          ]
     // [ orientation (3x1)] = [ 2 * delta_q(0:2) ]
-    Eigen::Map<Eigen::Matrix<T, 6, 1> > residuals(residuals_ptr);
+    Eigen::Map<Eigen::Matrix<T, 6, 1>> residuals(residuals_ptr);
     residuals.template block<3, 1>(0, 0) =
         p_ab_estimated - t_ab_measured_.p.template cast<T>();
     residuals.template block<3, 1>(3, 0) = T(2.0) * delta_q.vec();
diff --git a/examples/slam/pose_graph_3d/types.h b/examples/slam/pose_graph_3d/types.h
index 2f12501..d3f19ed 100644
--- a/examples/slam/pose_graph_3d/types.h
+++ b/examples/slam/pose_graph_3d/types.h
@@ -47,24 +47,24 @@
   Eigen::Quaterniond q;
 
   // The name of the data type in the g2o file format.
-  static std::string name() {
-    return "VERTEX_SE3:QUAT";
-  }
+  static std::string name() { return "VERTEX_SE3:QUAT"; }
 
   EIGEN_MAKE_ALIGNED_OPERATOR_NEW
 };
 
-std::istream& operator>>(std::istream& input, Pose3d& pose) {
-  input >> pose.p.x() >> pose.p.y() >> pose.p.z() >> pose.q.x() >>
-      pose.q.y() >> pose.q.z() >> pose.q.w();
+inline std::istream& operator>>(std::istream& input, Pose3d& pose) {
+  input >> pose.p.x() >> pose.p.y() >> pose.p.z() >> pose.q.x() >> pose.q.y() >>
+      pose.q.z() >> pose.q.w();
   // Normalize the quaternion to account for precision loss due to
   // serialization.
   pose.q.normalize();
   return input;
 }
 
-typedef std::map<int, Pose3d, std::less<int>,
-                 Eigen::aligned_allocator<std::pair<const int, Pose3d> > >
+typedef std::map<int,
+                 Pose3d,
+                 std::less<int>,
+                 Eigen::aligned_allocator<std::pair<const int, Pose3d>>>
     MapOfPoses;
 
 // The constraint between two vertices in the pose graph. The constraint is the
@@ -83,14 +83,12 @@
   Eigen::Matrix<double, 6, 6> information;
 
   // The name of the data type in the g2o file format.
-  static std::string name() {
-    return "EDGE_SE3:QUAT";
-  }
+  static std::string name() { return "EDGE_SE3:QUAT"; }
 
   EIGEN_MAKE_ALIGNED_OPERATOR_NEW
 };
 
-std::istream& operator>>(std::istream& input, Constraint3d& constraint) {
+inline std::istream& operator>>(std::istream& input, Constraint3d& constraint) {
   Pose3d& t_be = constraint.t_be;
   input >> constraint.id_begin >> constraint.id_end >> t_be;
 
@@ -105,7 +103,7 @@
   return input;
 }
 
-typedef std::vector<Constraint3d, Eigen::aligned_allocator<Constraint3d> >
+typedef std::vector<Constraint3d, Eigen::aligned_allocator<Constraint3d>>
     VectorOfConstraints;
 
 }  // namespace examples
diff --git a/examples/snavely_reprojection_error.h b/examples/snavely_reprojection_error.h
index 5e51eb4..eb39d23 100644
--- a/examples/snavely_reprojection_error.h
+++ b/examples/snavely_reprojection_error.h
@@ -70,15 +70,14 @@
     // Compute the center of distortion. The sign change comes from
     // the camera model that Noah Snavely's Bundler assumes, whereby
     // the camera coordinate system has a negative z axis.
-    const T xp = - p[0] / p[2];
-    const T yp = - p[1] / p[2];
+    const T xp = -p[0] / p[2];
+    const T yp = -p[1] / p[2];
 
     // Apply second and fourth order radial distortion.
     const T& l1 = camera[7];
     const T& l2 = camera[8];
-    const T r2 = xp*xp + yp*yp;
-    const T distortion = 1.0 + r2  * (l1 + l2  * r2);
-
+    const T r2 = xp * xp + yp * yp;
+    const T distortion = 1.0 + r2 * (l1 + l2 * r2);
 
     // Compute final projected point position.
     const T& focal = camera[6];
@@ -97,7 +96,7 @@
   static ceres::CostFunction* Create(const double observed_x,
                                      const double observed_y) {
     return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>(
-                new SnavelyReprojectionError(observed_x, observed_y)));
+        new SnavelyReprojectionError(observed_x, observed_y)));
   }
 
   double observed_x;
@@ -135,15 +134,15 @@
     // Compute the center of distortion. The sign change comes from
     // the camera model that Noah Snavely's Bundler assumes, whereby
     // the camera coordinate system has a negative z axis.
-    const T xp = - p[0] / p[2];
-    const T yp = - p[1] / p[2];
+    const T xp = -p[0] / p[2];
+    const T yp = -p[1] / p[2];
 
     // Apply second and fourth order radial distortion.
     const T& l1 = camera[8];
     const T& l2 = camera[9];
 
-    const T r2 = xp*xp + yp*yp;
-    const T distortion = 1.0 + r2  * (l1 + l2  * r2);
+    const T r2 = xp * xp + yp * yp;
+    const T distortion = 1.0 + r2 * (l1 + l2 * r2);
 
     // Compute final projected point position.
     const T& focal = camera[7];
@@ -161,10 +160,13 @@
   // the client code.
   static ceres::CostFunction* Create(const double observed_x,
                                      const double observed_y) {
-    return (new ceres::AutoDiffCostFunction<
-            SnavelyReprojectionErrorWithQuaternions, 2, 10, 3>(
-                new SnavelyReprojectionErrorWithQuaternions(observed_x,
-                                                            observed_y)));
+    return (
+        new ceres::AutoDiffCostFunction<SnavelyReprojectionErrorWithQuaternions,
+                                        2,
+                                        10,
+                                        3>(
+            new SnavelyReprojectionErrorWithQuaternions(observed_x,
+                                                        observed_y)));
   }
 
   double observed_x;