write crash file in case of trouble in mgmt thread

also refactor code