fix several bugs, ir almost finished