Cleaned code. Added exceptions to replace trigger_error.