Split up code for clarity, tried to fix soem bugs