cleaned up the code to make it more coherent