initial version from Muhibur and David with minor cleanup