Manual merge of the code in #171

Updated the code from #171 into a new PR.