Migrated functions from Hamid's misc_utilities.