fixed some bugs. there may be a mem leak on lastbuf