Swift implementation based on: http://arxiv.org/abs/1310.8499