A general formalism for the calculation of free energies of inhomogeneous dielectric and electrolytic systems