Analytical mechanics of gears