This kind of works but the logic in the main loop is ugly as hell