cleaned up code, made it a bit more dry, modular, fixed some bugs