Fixed more bugs added error checking
Refactored code, easier readability and better handling exception