Added I/O and logging; improved error handling.