Bug-fixes and refactoring.

Change-Id: I08e7bb98ef767e6b69fd9674de0d6ed0e55de429
Reviewed-on: http://review.couchbase.org/40609
Reviewed-by: John Liang <johliang00@gmail.com>
Reviewed-by: Pratap Chakravarthy <prataprc@couchbase.com>
Tested-by: Pratap Chakravarthy <prataprc@couchbase.com>