aks: rewrote the main loop; managed global vars correctly.