Working version. merged the work of Audun and sverre.