Reorganized, added error handling