fixed more error handling and implemented better code structure