Based on Emin's implementation from MIT website