Rigorous theory of the tunneling magnetoresistance (TMR) based on the real-space Kubo formula and fully realistic tight-binding bands fitted to an ab initio band structure is decribed. It is first applied to calculate the TMR of two Co electrodes separated by a vacuum gap. The calculated TMR ratio reaches some 65% in the tunneling regime but can be as high as 280% in the metallic regime when the vacuum gap is of the order of the Co interatomic distance (abrupt domain wall). It is also shown that the spin polarization P of the tunneling current is negative in the metallic regime but becomes positive P~35% in the tunneling regime. Calculation of the tunneling magnetoresistance of an epitaxial Fe/MgO/Fe(001) junction is also described. The calculated optimistic TMR ratio is in excess of 1000% for an MgO barrier with 20 atomic planes of MgO and the spin polarization of the tunneling current is positive for all MgO thicknesses. Finally, it is demonstrated that the TMR ratio calculated from the Kubo formula remains nonzero when one of the Co electrodes is covered with a copper layer. It is shown that nonzero TMR is due to quantum well states in the Cu layer which do not participate in transport. Since these only occur in the down-spin channel, their loss from transport creates a spin asymmetry of electrons tunneling from a Cu interlayer, i.e. nonzero TMR. Numerical modelling is used to show that diffuse scattering from a random distribution of impurities in the barrier may cause quantum well states to evolve into propagating states, in which case the average TMR tends to zero but large quantum oscillations of TMR about zero average remain.