Removed unused code and merged redundant code blocks where possible.