<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def fit_spectrum(self, specFunc, initPars, freePars=None):
 """ Fit for the free parameters of a spectral function Parameters specFunc : `~fermipy.spectrum.SpectralFunction` The Spectral Function initPars : `~numpy.ndarray` The initial values of the parameters freePars : `~numpy.ndarray` Boolean array indicating which parameters should be free in the fit. Returns ------- params : `~numpy.ndarray` Best-fit parameters. spec_vals : `~numpy.ndarray` The values of the best-fit spectral model in each energy bin. ts_spec : float The TS of the best-fit spectrum chi2_vals : `~numpy.ndarray` Array of chi-squared values for each energy bin. chi2_spec : float Global chi-squared value for the sum of all energy bins. pval_spec : float p-value of chi-squared for the best-fit spectrum. """

        if not isinstance(specFunc, SEDFunctor):
            specFunc = self.create_functor(specFunc, initPars,
                                           scale=specFunc.scale)

        if freePars is None:
            freePars = np.empty(len(initPars), dtype=bool)
            freePars.fill(True)

        initPars = np.array(initPars)
        freePars = np.array(freePars)

        def fToMin(x):

            xp = np.array(specFunc.params)
            xp[freePars] = x
            return self.__call__(specFunc(xp))

        result = fmin(fToMin, initPars[freePars], disp=False, xtol=1e-6)

        out_pars = specFunc.params
        out_pars[freePars] = np.array(result)

        spec_vals = specFunc(out_pars)
        spec_npred = np.zeros(len(spec_vals))

        if isinstance(specFunc, spectrum.SEDFluxFunctor):
            spec_npred = spec_vals * self.refSpec.ref_npred / self.refSpec.ref_flux
        elif isinstance(specFunc, spectrum.SEDEFluxFunctor):
            spec_npred = spec_vals * self.refSpec.ref_npred / self.refSpec.ref_eflux

        ts_spec = self.TS_spectrum(spec_vals)
        chi2_vals = self.chi2_vals(spec_vals)
        chi2_spec = np.sum(chi2_vals)
        pval_spec = stats.distributions.chi2.sf(chi2_spec, len(spec_vals))
        return dict(params=out_pars, spec_vals=spec_vals,
                    spec_npred=spec_npred,
                    ts_spec=ts_spec, chi2_spec=chi2_spec,
                    chi2_vals=chi2_vals, pval_spec=pval_spec)