Refactored pieces of original fundcode