I think you should use one function to do this kind of things. 'main' is too big now.