!-----------------------------------------------------------------------------
Subroutine Calc_Spells
Integer :: ist, ireg, NDot, MaxDot
Real :: X(Ntime), M(Ntime), Spell(Ntime), I_Start(Ntime), I_End(Ntime), Imax, NSpell
!Integer :: Max_So_Dot        ! So dot lon nhat cua tat ca cac tram (=Max {Ndot} - Gia tri lon nhat cua N_Spell)
!Integer :: Max_Length_Dot    ! Do keo dai dai nhat trong tat ca cac dot cua cac tram (=Max {MaxDot} - Gia tri lon nhat cua Imax)

! M(MaxDot): Luu tan so cua tung dot, tu 1,2,..,MaxDot; MaxDot la do dai cuc dai cua cac dot
! Spell(NDot): Luu do dai tung dot, tu 1,2,..,NDot; NDot la so dot trong toan chuoi
! I_Start(NDot), I_End(NDot): Luu chi so dau va cuoi cua tung dot
Dur1=Miss; Dur2=Miss; Dur3=Miss;  Spel1=Miss; Spel2=Miss; Spel3=Miss;
Max_So_Dot=0; Max_Length_Dot=0; Max_So_Dot_Reg=0; Max_Length_Dot_Reg=0
Do ist=1, Nst   ! Tinh tan so ung voi do dai tung dot va Tan so tung dot cua tung tram
   X(1:Ntime) = D1(ist,1:Ntime); Call NSpell_and_Leng (X, Ntime, M, Imax, Spell, NSpell, I_Start, I_End); MaxDot=Int(Imax); NDot=Int(NSpell)
   Dur1(ist,1:MaxDot)=M(1:MaxDot); Spel1(ist,1:NDot)=Spell(1:NDot); IS1(ist,1:NDot)=I_Start(1:NDot); IE1(ist,1:NDot)=I_End(1:NDot)
   N_Dur1(ist)=MaxDot; N_Spel1(ist)=NDot
   if (Max_Length_Dot<MaxDot) Max_Length_Dot=MaxDot; if (Max_So_Dot<NDot) Max_So_Dot=NDot

   X(1:Ntime) = D2(ist,1:Ntime); Call NSpell_and_Leng (X, Ntime, M, Imax, Spell, NSpell, I_Start, I_End); MaxDot=Int(Imax); NDot=Int(NSpell)
   Dur2(ist,1:MaxDot)=M(1:MaxDot); Spel2(ist,1:NDot)=Spell(1:NDot); IS2(ist,1:NDot)=I_Start(1:NDot); IE2(ist,1:NDot)=I_End(1:NDot)
   N_Dur2(ist)=MaxDot; N_Spel2(ist)=NDot
   if (Max_Length_Dot<MaxDot) Max_Length_Dot=MaxDot; if (Max_So_Dot<NDot) Max_So_Dot=NDot

   X(1:Ntime) = D3(ist,1:Ntime); Call NSpell_and_Leng (X, Ntime, M, Imax, Spell, NSpell, I_Start, I_End); MaxDot=Int(Imax); NDot=Int(NSpell)
   Dur3(ist,1:MaxDot)=M(1:MaxDot); Spel3(ist,1:NDot)=Spell(1:NDot); IS3(ist,1:NDot)=I_Start(1:NDot); IE3(ist,1:NDot)=I_End(1:NDot)
   N_Dur3(ist)=MaxDot; N_Spel3(ist)=NDot
   if (Max_Length_Dot<MaxDot) Max_Length_Dot=MaxDot; if (Max_So_Dot<NDot) Max_So_Dot=NDot
Enddo
End Subroutine Calc_Spells
!-----------------------------------------------------------------------------

