Fixed memory leak in apply_distributive_law, improved code formatting