set flags and cleanup