code refactoring and bug fix for decoding