Added some more error checks, fixed bug