Error logging; improved file handling