I am pretty happy with this code, but it needs to be tested