Simplify the repetitive code part (about 25 lines are the same)