modified & enhanced by zhs490770, orginally from online_judger