fix syntax mistake and rearrange logic