Restructured and modified code to match latest internally used version