Major Code Cleanup with several bug fixes