Complete rewrite and implementation of option added in 881f993