How can I make compilation to go through with a module inside module? I tried this, failed, a few other ways failed too. f = Compile[{{\[Sigma]t, _Real, 1}, {s\[Rho], _Complex, 1}, {dt, _Real, 1}, {x, _Real}, {nnt, _Integer}, {dqt, _Real}, {divt, _Integer}}, Module[{temp, dq = dqt, div = divt, j, h}, temp[x_] := Module[{kz = 1/2 x, \[Sigma] = \[Sigma]t, d = dt, i, kp, c, \[Beta], r, k, \[Rho] = s\[Rho] * 10^-6, nn = nnt}, kp = kz + 0. I; k = Sqrt[kz^2 - 4 \[Pi] (\[Rho][[2]] - \[Rho][[1]])]; r = (kp - k)/(kp + k) E^(-2 kp k \[Sigma][[1]]^2); c = {{1 + 0. I, r }, {r , 1}}; kp = k; For[i = 2, i < 2 nn + 2, i++, If[EvenQ[i], k = Sqrt[kz^2 - 4 \[Pi] (\[Rho][[3]] - \[Rho][[1]])]; r = (kp - k)/(kp + k) E^(-2 kp k \[Sigma][[2]]^2); \[Beta] = I kp d[[1]], k = Sqrt[kz^2 - 4 \[Pi] (\[Rho][[2]] - \[Rho][[1]])]; r = (kp - k)/(kp + k) E^(-2 kp k \[Sigma][[3]]^2); \[Beta] = I kp d[[2]] ]; c = c.{{E^\[Beta], r E^\[Beta]}, {r E^-\[Beta], E^-\[Beta]}}; (*previous k*) kp = k ]; Abs[c[[2, 1]]/c[[1, 1]]]^2]; h = 0.0; For[j = 1, j < div + 1, j++, h = h + temp[x - dq/2 + dq/div*j] ]; h/div ] , CompilationTarget -> "C"]