Reordered output and semaphores to properly synchronize the output.