Importing some code from the decode-state branch.