Finished AFC and fixed file writing
WARNING: UNTESTED!!!