Originally written by Ronald S. Bultje, with fixes, optimizations and improvements by James Almer. Signed-off-by: James Almer <jamrial@gmail.com>