Bug fixes
Also cleaned the code