On the formation of spiral and elliptical galaxies