Copied several functions from jelephant for HBP review