Base code from Johan.