Some fixes, cleaned up the code