AFD logic, but not tested yet