code cleanup: const correctness and general c++ improvements

use pair<iter,bool> map<k,v>::insert(...) instead of causing multiple
lookups.

don't make so many copies of everything all the time (use
refs/constrefs).