some refactoring and err function fixes