Using bulk insert where appropriate.

and other refactoring.