remove unused imports; add output redirection detect; add return code; simplify and refine