Ugly code. Attempt at single thread.