Refactored decoding function.