Cleaned up and optimized code.  Still needs tested;: