reorganized the code a bit