scrapped nested loops, trying state machine