Fixed some bugs, added some safety checks and added some error messages.