Seems to be working. Cleaned up code