Fix access violation and rework code