Adapted from Mathematica code I wrote in 2010/2011