#! /bin/ksh

set -e

typeset byte=''
typeset STATE='START'
typeset high_length=''
typeset -i length=0
typeset TYPE=''
typeset -i RECORD=0
typeset high_record=''

function record_type
{
  case "$1" in
    D3A788) print "MMC (Medium Modification Cntl)." ;;
    *) print "Record type: ${1}." ;;
  esac
} # function record_type

#for byte in $( b2x "$1" )
for byte in \
5A 00 14 D3 A7 88 00 00 B2 01 FF D1 01 E0 02 E1 00 F4 02 F9 00
do
  case "${STATE}" in
    START)
      if [[ "${byte}" = '5A' ]]
      then
        STATE='HIGH_LENGTH'
      else
        STATE='LOW_LENGTH'
        high_length="${byte}"
      fi
      ;;
    HIGH_LENGTH)
      high_length="${byte}"
      STATE='LOW_LENGTH'
      ;;
    LOW_LENGTH)
      length="16#${high_length}${byte}"
      print "Length: ${length}."
      STATE='TYPE_HIGH'
      ;;
    TYPE_HIGH)
      TYPE="${byte}"
      STATE='TYPE_MIDDLE'
      ;;
    TYPE_MIDDLE)
      TYPE="${TYPE}${byte}"
      STATE='TYPE_LOW'
      ;;
    TYPE_LOW)
      TYPE="${TYPE}${byte}"
      record_type "${TYPE}"
      STATE='FLAG'
      ;;
    FLAG)
      STATE='HIGH_RECORD'
      ;;
    HIGH_RECORD)
      high_record="${byte}"
      STATE='LOW_RECORD'
      ;;
    LOW_RECORD)
      RECORD="16#${high_record}${byte}"
      print "Record number: ${RECORD}."
      length=length-8
      STATE='PAYLOAD'
      ;;
    PAYLOAD)
      print -n "${byte}"
      length=length-1
      ;;
    *) print -u2 "Unknown byte: ${STATE}, bailing out!" ; exit 1 ;;
  esac
done

if (( length != 0 ))
then
  print -u2 "Error:Bytes left: ${length}"
  exit 1
else
  print
fi

exit 0

################ EOF ################
