Cleaned up some code with help of Keith; work in progress