If all commands are 3 characters long except CMDxxx which is 6, it is not that complicated to do.
If the string read has more than 3 characters, you confirm that it contains "CMD" as I suggested in #5 and then extract the number.
Otherwise (it would have 3 characters), you execute the statements corresponding to those commands.