cleaned up. some functions can probably be deleted. untested.