!-----------------------------------------------------------------------------
Subroutine Calc_Spells
Integer :: ilon, ilat, 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 ilon=1, Nlon   ! Tinh tan so ung voi do dai tung dot va Tan so tung dot cua tung tram
   Do ilat=1, Nlat
      if (Reg(ilon,ilat)>=1.AND.Reg(ilon,ilat)<=Nreg) then
         X(1:Ntime) = D1(ilon,ilat,1:Ntime); Call NSpell_and_Leng (X, Ntime, M, Imax, Spell, NSpell, I_Start, I_End); MaxDot=Int(Imax); NDot=Int(NSpell)
!print*, "D1=",X(1:Ntime)
!print*, "Spell Freq=",M(1:Ntime)
!print*, "NSpell=", NSpell
         Dur1(ilon,ilat,1:MaxDot)=M(1:MaxDot); Spel1(ilon,ilat,1:NDot)=Spell(1:NDot); IS1(ilon,ilat,1:NDot)=I_Start(1:NDot); IE1(ilon,ilat,1:NDot)=I_End(1:NDot)
         N_Dur1(ilon,ilat)=MaxDot; N_Spel1(ilon,ilat)=NDot
         if (Max_Length_Dot<MaxDot) Max_Length_Dot=MaxDot; if (Max_So_Dot<NDot) Max_So_Dot=NDot

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

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

