reorganized code a bit