Reworked code out of main()