Reduced code + fixed some bugs.