Fixed buffer space bug.
Added buffer clear and error check.