Based on @KhashayarDanesh's work in #1269, which is also based on the work of @sstent and @povik. Closes #1269