An adaptive Metropolis-Hastings scheme: Sampling and optimization