Cleaned up a bit of the code. Wrapped writing to a file in a semaphore.