final code with working Hidden Markov Model function