Refactoring and XTSM bug fix