Improve reference handling

Related to #803