General code quality improvements and potential bug fixes
fixed all casting issues.