Measurement of D∗ meson cross sections at HERA and determination of the gluon density in the proton using NLO QCD