Some code reorganization.

- Move utility functions to bottom of file.
- Use encode and decode functions for EMSA.