patched to fix bugs