Merged some code by Lorenzo