Stability fixes & code reorganization.

Updated for SDK 4.2.1