Code from version 2.0RC7 by RafahFoster