A few bugs fixed + a little refactoring