Refactored apfy.js and corrected state machine bugs in test_apfy.html