Refactored code

Removed unnecessary includes
Added exceptions & basic exception handling
Extracted parts of code from long functions and gave them their own
function