Some optimizations and logic error fixations