Major cod cleanup/bug fixes