removed the use of unsafe and reviewed as much as possible