Fixed function apply bugs. Cleaned up code for readability.