factored code. fixed a bunch of c craziness, lack of casting, etc *IDONTKNOWWHATIMDOING*