subroutine Pump_and_TripIn    !  is called in subroutine CirculationCodeSelect
    
        Use GeoElements_FluidModule
        USE CMudPropertiesVariables
        USE MudSystemVARIABLES
use SimulationVariables !@@@
        use SimulationVariables
        USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !use CDataDisplayConsole
   !@ use ConfigurationVariables ,  StandPipePressureDataDisplay=>StandPipePressure
        !use CManifolds
        use SimulationVariables !@
        USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !use CChokeManifoldVariables
    use SimulationVariables
        !use CTanks
    !@use ConfigurationVariables, TripTankVolume2 => data%EquipmentControl%DrillingWatch%TripTankVolume, TripTankDensity2 => TripTankDensity
        USE sROP_Other_Variables
        USE sROP_Variables
        use KickVARIABLESModule
        Use CShoeVariables
        use CError

   
   implicit none
   
integer i,ii,AddLocation
!===========================================================WELL============================================================
!===========================================================WELL============================================================ 

        data%State%MudSystem%StringFlowRate= data%State%MUD(2)%Q
        data%State%MudSystem%AnnulusFlowRate= data%State%MUD(2)%Q

        
            !write(*,*) 'Trip In'
  

!========================Horizontal PIPE ENTRANCE================= 
        
         if (ABS(data%State%MudSystem%SuctionDensity_Old - data%State%MudSystem%Suction_Density_MudSystem) >= data%State%MudSystem%DensityMixTol) then     ! new mud is pumped
             
            call data%State%MudSystem%Hz_Density%AddToFirst (data%State%MudSystem%Suction_Density_MudSystem)
            call data%State%MudSystem%Hz_MudDischarged_Volume%AddToFirst (0.0d0)
            call data%State%MudSystem%Hz_Mud_Forehead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(1))
            call data%State%MudSystem%Hz_Mud_Forehead_section%AddToFirst (1)
            call data%State%MudSystem%Hz_Mud_Backhead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(1))
            call data%State%MudSystem%Hz_Mud_Backhead_section%AddToFirst (1)
            call data%State%MudSystem%Hz_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
            call data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
            call data%State%MudSystem%Hz_MudOrKick%AddToFirst (0)  
             
             data%State%MudSystem%SuctionDensity_Old= data%State%MudSystem%Suction_Density_MudSystem
         endif

!========================Horizontal PIPE STRING================= 
         
                data%State%MudSystem%Hz_MudDischarged_Volume%Array(1)= data%State%MudSystem%Hz_MudDischarged_Volume%Array(1)+ ((data%State%MudSystem%StringFlowRate/60.0d0)*data%State%MudSystem%DeltaT_Mudline)    !(gal)
                
                data%State%MudSystem%total_add = data%State%MudSystem%total_add + ((data%State%MudSystem%StringFlowRate/60.0d0)*data%State%MudSystem%DeltaT_Mudline)
                
                    if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
                        data%State%MudSystem%total_add= 0.
                    endif                   
                
                
        !write(*,*) ' total decrease(add to HZ)=' , total_add
                !write(*,*) ' add to HZ=' , ((data%State%MudSystem%StringFlowRate/60.0d0)*DeltaT_Mudline)                

imud=0       
    do while (imud < data%State%MudSystem%Hz_Mud_Forehead_X%Length())
        imud = imud + 1 
        
            if (imud> 1) then
                data%State%MudSystem%Hz_Mud_Backhead_X%Array(imud)= data%State%MudSystem%Hz_Mud_Forehead_X%Array(imud-1)
                data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud)= data%State%MudSystem%Hz_Mud_Forehead_section%Array(imud-1)
            endif

                
            data%State%MudSystem%DirectionCoef= (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud))) &
                / ABS(data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud)))
            ! +1 for string  ,   -1 for annulus
                
                                                                                                                    
            data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%DirectionCoef* (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud))- data%State%MudSystem%Hz_Mud_Backhead_X%Array(imud))* &
                data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud)) !(ft^3)          
            data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%Array(imud)* 7.48051948d0        ! ft^3  to gal
            

            if ( data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud) <= data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%Array(imud)) then
                data%State%MudSystem%Hz_Mud_Forehead_section%Array(imud)= data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud)
                data%State%MudSystem%Hz_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Hz_Mud_Backhead_X%Array(imud)+ data%State%MudSystem%DirectionCoef*(data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud)/7.48051948d0)/data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud))
                
            else
                
                
                data%State%MudSystem%isection= data%State%MudSystem%Hz_Mud_Backhead_section%Array(imud)+1
                data%State%MudSystem%Hz_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Hz_EmptyVolume_inBackheadLocation%Array(imud)
                    
                do 
                        if (data%State%MudSystem%isection > 1) then        ! (horizontal pipe exit)
                            data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud)= data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Hz_RemainedVolume_in_LastSection%Array(imud)
                            data%State%MudSystem%Hz_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Xend_PipeSection(1)
                            data%State%MudSystem%Hz_Mud_Forehead_section%Array(imud)= 1
                            
                            if (data%State%MudSystem%Hz_MudDischarged_Volume%Array(imud)<= 0.0d0)  then    ! imud is completely exited form the string
                                call RemoveHzMudArrays(imud)
                            endif
                            
                            exit
                        endif
                                 
                    data%State%MudSystem%xx= data%State%MudSystem%Hz_RemainedVolume_in_LastSection%Array(imud)/ data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)   !(gal)
                        
                    if (data%State%MudSystem%xx<= 1.0) then
                        data%State%MudSystem%Hz_Mud_Forehead_section%Array(imud)= data%State%MudSystem%isection
                        data%State%MudSystem%Hz_Mud_Forehead_X%Array(imud)= (data%State%MudSystem%xx * (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%isection)- data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)))+ data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)
                        exit
                    else
                        data%State%MudSystem%Hz_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Hz_RemainedVolume_in_LastSection%Array(imud)- data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)
                        data%State%MudSystem%isection= data%State%MudSystem%isection+ 1
                                                      
                    endif

                enddo
            
            endif   
        
    enddo
!========================Horizontal PIPE END=================         
            
        
!========================Utube1 Air Element Removing=================         
    
        !if (UtubeMode1Activated== .true.) then      ! StringUpdate == .true.
        !
        !
        !    !StringDensity_Old=data%State%MudSystem%St_Density%Array(2)
        !    
        !    write(*,*) 'StringDensity_Old=' , StringDensity_Old
        !    
        !    UtubeMode1Activated= .false.
        !endif
        
!========================Utube1 Air Element Removing End=================       
       
!!========================Utube2 Removing from Annulus=================     not needed 97.04.26    
!    
!        if (UtubeMode2Activated== .true.) then      ! StringUpdate == .true.
!            
!            if (Ann_MudOrKick%Last() == 104) then        !movaghati. albate age merge anjam shode bashe moshkeli nist
!                call RemoveAnnulusMudArrays(Ann_MudOrKick%Length())
!            endif
!            
!            UtubeMode2Activated= .false.
!        endif
!        
!
!!========================Utube2 Removing from Annulus End=================  
        
!========================New Pipe Filling=================         
    
        !if (F_StringIntervalCounts > F_StringIntervalCountsOld) then      ! StringUpdate == .true.
        if (data%State%MudSystem%AddedElementsToString > 0) then      ! StringUpdate == .true.
            
            !NoPipeAdded= data%State%F_Counts%StringIntervalCounts - F_StringIntervalCountsOld

            
            data%State%MudSystem%NewPipeFilling=0
            
            IF (data%State%MudSystem%St_MudOrKick%First() == 104) then
                data%State%MudSystem%St_MudDischarged_Volume%Array(1) = data%State%MudSystem%St_MudDischarged_Volume%Array(1) + sum(data%State%MudSystem%PipeSection_VolumeCapacity(2:1+data%State%MudSystem%AddedElementsToString))   ! new pipe is filled by air
            else
                call data%State%MudSystem%St_Density%AddToFirst (0.d0)
                call data%State%MudSystem%St_MudDischarged_Volume%AddToFirst (sum(data%State%MudSystem%PipeSection_VolumeCapacity(2:1+data%State%MudSystem%AddedElementsToString)))
                call data%State%MudSystem%St_Mud_Forehead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(2))
                call data%State%MudSystem%St_Mud_Forehead_section%AddToFirst (2)
                call data%State%MudSystem%St_Mud_Backhead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(2))
                call data%State%MudSystem%St_Mud_Backhead_section%AddToFirst (2)
                call data%State%MudSystem%St_RemainedVolume_in_LastSection%AddToFirst (0.d0)
                call data%State%MudSystem%St_EmptyVolume_inBackheadLocation%AddToFirst (0.d0)
                call data%State%MudSystem%St_MudOrKick%AddToFirst (104)
            endif

        endif
        
        !F_StringIntervalCountsOld= F_StringIntervalCounts
    
        
            
          if (data%State%MudSystem%NewPipeFilling == 0) then  ! 2= is the first element of string (1= is for Hz pipe)
              
                
                data%State%MudSystem%LackageMudVolume= data%State%MudSystem%St_MudDischarged_Volume%Array(1)      ! = Air element
                
                
              write(*,*) 'LackageMudVolume=' , data%State%MudSystem%LackageMudVolume

           
            
                 if (ABS(data%State%MudSystem%St_Density%Array(2) - data%State%MudSystem%Hz_Density%Last()) >= data%State%MudSystem%DensityMixTol) then     ! new mud is pumped
                    call data%State%MudSystem%St_Density%AddTo (2,data%State%MudSystem%Hz_Density%Last())
                    call data%State%MudSystem%St_MudDischarged_Volume%AddTo (2, 0.d0)
                    call data%State%MudSystem%St_Mud_Forehead_X%AddTo (2,data%State%MudSystem%Xstart_PipeSection(2))
                    call data%State%MudSystem%St_Mud_Forehead_section%AddTo (2 , 2)
                    call data%State%MudSystem%St_Mud_Backhead_X%AddTo (2,data%State%MudSystem%Xstart_PipeSection(2))
                    call data%State%MudSystem%St_Mud_Backhead_section%AddTo (2 ,2)
                    call data%State%MudSystem%St_RemainedVolume_in_LastSection%AddTo (2,0.d0)
                    call data%State%MudSystem%St_EmptyVolume_inBackheadLocation%AddTo (2,0.d0)
                    call data%State%MudSystem%St_MudOrKick%AddTo (2,0)
             
                     !StringDensity_Old= Hz_Density%Last()
                 endif 
                

                data%State%MudSystem%St_MudDischarged_Volume%Array(2)= data%State%MudSystem%St_MudDischarged_Volume%Array(2)+ min( ((data%State%MudSystem%StringFlowRate/60.0d0)*data%State%MudSystem%DeltaT_Mudline), data%State%MudSystem%LackageMudVolume)  !(gal) 
                
                data%State%MudSystem%St_MudDischarged_Volume%Array(1)= data%State%MudSystem%St_MudDischarged_Volume%Array(1)- min( ((data%State%MudSystem%StringFlowRate/60.0d0)*data%State%MudSystem%DeltaT_Mudline), data%State%MudSystem%LackageMudVolume)  ! air(gal) 
    
                !LackageMudVolumeAfterFilling= sum(PipeSection_VolumeCapacity(2:F_StringIntervalCounts)) - sum(St_MudDischarged_Volume%Array(:))
                
                data%State%MudSystem%LackageMudVolumeAfterFilling= data%State%MudSystem%St_MudDischarged_Volume%Array(1)      ! last time it should be zero
                
                
                
                if (data%State%MudSystem%LackageMudVolumeAfterFilling == 0.) then
                    data%State%MudSystem%NewPipeFilling= 1
                    call RemoveStringMudArrays(1)
                    data%State%MudSystem%St_Mud_Backhead_X%Array(1) = data%State%MudSystem%Xstart_PipeSection(2)
                    data%State%MudSystem%St_Mud_Backhead_section%Array(1) = 2
                endif
                
          endif

!========================New Pipe Filling End=================       
        
        
        
        
        if (data%State%MudSystem%NewPipeFilling == 0) then
            data%State%MudSystem%StringFlowRate= 0.
            data%State%MudSystem%AnnulusFlowRate= 0.
        endif  
        
        data%State%MudSystem%StringFlowRateFinal= data%State%MudSystem%StringFlowRate
        data%State%MudSystem%AnnulusFlowRateFinal= data%State%MudSystem%AnnulusFlowRate
        

        
          
!========================STRING ENTRANCE================= 
        
         if (data%State%MudSystem%StringFlowRateFinal > 0.0 .and. ABS(data%State%MudSystem%St_Density%First() - data%State%MudSystem%Hz_Density%Last()) >= data%State%MudSystem%DensityMixTol) then     ! new mud is pumped
            call data%State%MudSystem%St_Density%AddToFirst (data%State%MudSystem%Hz_Density%Last())
            call data%State%MudSystem%St_MudDischarged_Volume%AddToFirst (0.0d0)
            call data%State%MudSystem%St_Mud_Forehead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(2))
            call data%State%MudSystem%St_Mud_Forehead_section%AddToFirst (2)
            call data%State%MudSystem%St_Mud_Backhead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(2))
            call data%State%MudSystem%St_Mud_Backhead_section%AddToFirst (2)
            call data%State%MudSystem%St_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
            call data%State%MudSystem%St_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
            call data%State%MudSystem%St_MudOrKick%AddToFirst (0)
             
             !StringDensity_Old= Hz_Density%Last()
         endif
         
         
                data%State%MudSystem%St_MudDischarged_Volume%Array(1)= data%State%MudSystem%St_MudDischarged_Volume%Array(1)+ ((data%State%MudSystem%StringFlowRate/60.0d0)*data%State%MudSystem%DeltaT_Mudline)    !(gal)
           
!=============== save String Mud data=========== 
                
             
        
                
    data%State%MudSystem%StMudVolumeSum= 0.d0
    !St_MudSaved_Density= 0.d0
    data%State%MudSystem%St_Saved_MudDischarged_Volume= 0.d0
    !Saved_St_MudOrKick= 0
    !Ann_to_Choke_2mud= .false.

    do imud=1, data%State%MudSystem%St_MudDischarged_Volume%Length()
        
            data%State%MudSystem%StMudVolumeSum = data%State%MudSystem%StMudVolumeSum + data%State%MudSystem%St_MudDischarged_Volume%Array(imud)
        
        if ( data%State%MudSystem%StMudVolumeSum > sum(data%State%MudSystem%PipeSection_VolumeCapacity(2:data%State%F_Counts%StringIntervalCounts)) ) then
            
            !IF (St_MudOrKick%Array(imud) == 0) THEN
                data%State%MudSystem%St_MudSaved_Density =data%State%MudSystem%St_Density%Array(imud)
                data%State%MudSystem%St_Saved_MudDischarged_Volume = data%State%MudSystem%StMudVolumeSum - sum(data%State%MudSystem%PipeSection_VolumeCapacity(2:data%State%F_Counts%StringIntervalCounts))
            !ELSEIF (St_MudOrKick%Array(imud) > 0 .AND. St_MudOrKick%Array(imud) <100) THEN        ! 104= AIR
            !    St_Kick_Saved_Volume = StMudVolumeSum - sum(PipeSection_VolumeCapacity(F_StringIntervalCounts+1:NoPipeSections))
            !    Saved_St_MudOrKick= St_MudOrKick%Array (imud)
            !    St_KickSaved_Density=data%State%MudSystem%St_Density%Array(imud)
            !END IF
            
            do ii= imud + 1, data%State%MudSystem%St_MudDischarged_Volume%Length()
                !IF (St_MudOrKick%Array(ii) == 0) THEN
                    data%State%MudSystem%St_MudSaved_Density = ((data%State%MudSystem%St_MudSaved_Density * data%State%MudSystem%St_Saved_MudDischarged_Volume) + (data%State%MudSystem%St_Density%Array(ii) * data%State%MudSystem%St_MudDischarged_Volume%Array(ii))) / (data%State%MudSystem%St_Saved_MudDischarged_Volume + data%State%MudSystem%St_MudDischarged_Volume%Array(ii))
                    data%State%MudSystem%St_Saved_MudDischarged_Volume = data%State%MudSystem%St_Saved_MudDischarged_Volume + data%State%MudSystem%St_MudDischarged_Volume%Array(ii)

                !ELSEIF (St_MudOrKick%Array(imud) > 0 .AND. St_MudOrKick%Array(imud) <100) THEN        ! 104= AIR
                !    St_Kick_Saved_Volume = St_Kick_Saved_Volume + St_MudDischarged_Volume%Array(ii)
                !    Saved_St_MudOrKick= St_MudOrKick%Array (ii)
                !    St_KickSaved_Density=data%State%MudSystem%St_Density%Array(ii)
                !END IF
            enddo
            
            
            !WRITE (*,*) 'St_Saved_Mud_Volume, St_Kick_Saved_Volume', St_Saved_MudDischarged_Volume, St_Kick_Saved_Volume
            exit ! exits do
            
        endif
        
    enddo
data%State%MudSystem%St_Saved_MudDischarged_Volume_Final = data%State%MudSystem%St_Saved_MudDischarged_Volume

IF (data%State%MudSystem%WellHeadIsOpen)     data%State%MudSystem%MudVolume_InjectedToBH = data%State%MudSystem%St_Saved_MudDischarged_Volume_Final
!======================================================================                
                
!========================STRING================= 
                      
imud=0  
    do while (imud < data%State%MudSystem%St_Mud_Forehead_X%Length())
        imud = imud + 1        
        
            if (imud> 1) then
                data%State%MudSystem%St_Mud_Backhead_X%Array(imud)= data%State%MudSystem%St_Mud_Forehead_X%Array(imud-1)
                data%State%MudSystem%St_Mud_Backhead_section%Array(imud)= data%State%MudSystem%St_Mud_Forehead_section%Array(imud-1)
            endif        
                     
            data%State%MudSystem%DirectionCoef= (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%St_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%St_Mud_Backhead_section%Array(imud))) &
                / ABS(data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%St_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%St_Mud_Backhead_section%Array(imud)))
            ! +1 for string  ,   -1 for annulus
                
                                                                                                                    
            data%State%MudSystem%St_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%DirectionCoef* (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%St_Mud_Backhead_section%Array(imud))- data%State%MudSystem%St_Mud_Backhead_X%Array(imud))* &
                data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%St_Mud_Backhead_section%Array(imud)) !(ft^3)          
            data%State%MudSystem%St_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%St_EmptyVolume_inBackheadLocation%Array(imud)* 7.48051948d0       ! ft^3  to gal
            
            
            !write(*,*) 'St_Mud_Backhead_section%Array(1)=' , St_Mud_Backhead_section%Array(1)
            !write(*,*) 'Xend_PipeSection(St_Mud_Backhead_section%Array(1))=' , Xend_PipeSection(St_Mud_Backhead_section%Array(1))
            !
            !write(*,*) 'St_EmptyVolume_inBackheadLocation%Array(1)=' , St_EmptyVolume_inBackheadLocation%Array(1)
            !write(*,*) 'St_Mud_Backhead_X%Array(1)=' , St_Mud_Backhead_X%Array(1)
            
            
            if ( data%State%MudSystem%St_MudDischarged_Volume%Array(imud) <= data%State%MudSystem%St_EmptyVolume_inBackheadLocation%Array(imud)) then
                data%State%MudSystem%St_Mud_Forehead_section%Array(imud)= data%State%MudSystem%St_Mud_Backhead_section%Array(imud)
                data%State%MudSystem%St_Mud_Forehead_X%Array(imud)= data%State%MudSystem%St_Mud_Backhead_X%Array(imud)+ data%State%MudSystem%DirectionCoef*(data%State%MudSystem%St_MudDischarged_Volume%Array(imud)/7.48051948d0)/data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%St_Mud_Backhead_section%Array(imud))
                                                                            !   7.48 is for gal to ft^3
                
            else
                    
                data%State%MudSystem%isection= data%State%MudSystem%St_Mud_Backhead_section%Array(imud)+1
                data%State%MudSystem%St_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%St_MudDischarged_Volume%Array(imud)- data%State%MudSystem%St_EmptyVolume_inBackheadLocation%Array(imud)
                    
                do 
                        if (data%State%MudSystem%isection > data%State%F_Counts%StringIntervalCounts) then        ! last pipe section(string exit) data%State%F_Counts%StringIntervalCounts includes Horizontal line
                            data%State%MudSystem%St_MudDischarged_Volume%Array(imud)= data%State%MudSystem%St_MudDischarged_Volume%Array(imud)- data%State%MudSystem%St_RemainedVolume_in_LastSection%Array(imud)
                            data%State%MudSystem%St_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Xend_PipeSection(data%State%F_Counts%StringIntervalCounts)
                            data%State%MudSystem%St_Mud_Forehead_section%Array(imud)= data%State%F_Counts%StringIntervalCounts
                            
                            if (data%State%MudSystem%St_MudDischarged_Volume%Array(imud)<= 0.0d0)  then     ! imud is completely exited form the string
                                call RemoveStringMudArrays(imud)
                            endif
                            
                            exit
                        endif
                                 
                    data%State%MudSystem%xx= data%State%MudSystem%St_RemainedVolume_in_LastSection%Array(imud)/ data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)   !(gal)
                        
                    if (data%State%MudSystem%xx<= 1.0) then
                        data%State%MudSystem%St_Mud_Forehead_section%Array(imud)= data%State%MudSystem%isection
                        data%State%MudSystem%St_Mud_Forehead_X%Array(imud)= (data%State%MudSystem%xx * (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%isection)- data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)))+ data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)
                        exit
                    else
                        data%State%MudSystem%St_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%St_RemainedVolume_in_LastSection%Array(imud)- data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)
                        data%State%MudSystem%isection= data%State%MudSystem%isection+ 1
                        
                                
                    endif

                enddo
            
            endif   

    enddo
    
    
    !write(*,*) ' a before=='
    !    
    !    do imud=1, Op_MudDischarged_Volume%Length()
    !        write(*,*) 'Op:', imud, Op_MudDischarged_Volume%Array(imud), Op_Density%Array(imud) ,Op_MudOrKick%Array(imud)
    !    enddo             
    !    
    !    do imud=1, Ann_MudDischarged_Volume%Length()
    !        write(*,*) 'Ann:', imud, Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud) ,Ann_MudOrKick%Array(imud)
    !    enddo
    !
    !write(*,*) '==== a before'     
    
    
    
    
 !write(*,*) ' iloc (a): ' , iloc   
    
!========================STRING END=================
    
    IF (data%State%MudSystem%Op_MudOrKick%Last() /= 0 .and. data%State%MudSystem%Op_MudOrKick%Last()==data%State%MudSystem%Ann_MudOrKick%First())  data%State%MudSystem%iLoc=2   ! it may be 1,2,3 or more,  all of them are kick 
!write(*,*) ' iloc (b): ' , iloc

!=============================Add PumpFlowRate to Bottom Hole ==============================    
        !if ( data%State%MudSystem%AnnulusFlowRate>0.0 ) then 
        if ( data%State%MudSystem%MudVolume_InjectedToBH > 0.0 ) then 
            
            
                if (KickVARIABLES%KickOffBottom) then                         ! (kickOffBottom = F) means kick is next to the bottom hole and usually kick is entering the
                    AddLocation= data%State%MudSystem%Op_Density%Length()-data%State%MudSystem%iLoc+1+1    ! well, thus pumped mud should be placed above the kick
                else
                    AddLocation= data%State%MudSystem%Op_Density%Length()+1
                endif
 !write(*,*) 'AddLocation====' , AddLocation
                if ( AddLocation== 0)      CALL ErrorStop ('AddLocation=0')
 
                
                if ( ABS(data%State%MudSystem%St_Density%Last() - data%State%MudSystem%Op_Density%Array(AddLocation-1)) >= data%State%MudSystem%DensityMixTol ) then
                    !write(*,*) 'new pocket**'
                    !write(*,*) data%State%MudSystem%St_Density%Last()=' ,data%State%MudSystem%St_Density%Last()
                    !write(*,*) 'Op_Density%Array(AddLocation-1)=' , Op_Density%Array(AddLocation-1)
                    

                    call data%State%MudSystem%Op_Density% AddTo (AddLocation,data%State%MudSystem%St_Density%Last())
                    !call Op_MudDischarged_Volume%AddTo (AddLocation,((data%State%MudSystem%AnnulusFlowRate/60.d0)*DeltaT_Mudline))
                    call data%State%MudSystem%Op_MudDischarged_Volume%AddTo (AddLocation,data%State%MudSystem%MudVolume_InjectedToBH)
                    call data%State%MudSystem%Op_Mud_Forehead_X%AddTo (AddLocation,data%State%MudSystem%Xstart_OpSection(1))
                    call data%State%MudSystem%Op_Mud_Forehead_section%AddTo (AddLocation,1)
                    call data%State%MudSystem%Op_Mud_Backhead_X%AddTo (AddLocation,data%State%MudSystem%Xstart_OpSection(1))
                    call data%State%MudSystem%Op_Mud_Backhead_section%AddTo (AddLocation,1)
                    call data%State%MudSystem%Op_RemainedVolume_in_LastSection%AddTo (AddLocation,0.0d0)
                    call data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%AddTo (AddLocation,0.0d0)
                    call data%State%MudSystem%Op_MudOrKick%AddTo (AddLocation,0) 
                else
                    !write(*,*) 'merge**'
                    !write(*,*) 'density before=' , Op_Density%Array(AddLocation-1)
                    !write(*,*) data%State%MudSystem%St_Density%Last() for mix=' ,data%State%MudSystem%St_Density%Last()
       
                    !Op_Density%Array(AddLocation-1)= (Op_Density%Array(AddLocation-1)*Op_MudDischarged_Volume%Array(AddLocation-1)data%State%MudSystem%St_Density%Last()*((data%State%MudSystem%AnnulusFlowRate/60.d0)*DeltaT_Mudline))/(Op_MudDischarged_Volume%Array(AddLocation-1)+((data%State%MudSystem%AnnulusFlowRate/60.d0)*DeltaT_Mudline))
                    !Op_MudDischarged_Volume%Array(AddLocation-1)= Op_MudDischarged_Volume%Array(AddLocation-1) + ((data%State%MudSystem%AnnulusFlowRate/60.d0)*DeltaT_Mudline)
                    
                    data%State%MudSystem%Op_Density%Array(AddLocation-1)= (data%State%MudSystem%Op_Density%Array(AddLocation-1)*data%State%MudSystem%Op_MudDischarged_Volume%Array(AddLocation-1)+data%State%MudSystem%St_Density%Last()*data%State%MudSystem%MudVolume_InjectedToBH)/(data%State%MudSystem%Op_MudDischarged_Volume%Array(AddLocation-1)+data%State%MudSystem%MudVolume_InjectedToBH)
                    data%State%MudSystem%Op_MudDischarged_Volume%Array(AddLocation-1)= data%State%MudSystem%Op_MudDischarged_Volume%Array(AddLocation-1) + data%State%MudSystem%MudVolume_InjectedToBH
                    !write(*,*) 'density after=' ,   Op_Density%Array(AddLocation-1)
                    
                endif
    
        endif   
!=======================Add PumpFlowRate to Bottom Hole- End ==============================    
    
    

    
!=============== save OP Mud data to transfer to the annulus enterance due to tripin or kick    
    data%State%MudSystem%OpMudVolumeSum= 0.d0
    !Op_MudSaved_Density= 0.d0
    !Op_KickSaved_Density= 0.d0
    data%State%MudSystem%Op_Saved_MudDischarged_Volume= 0.d0
    data%State%MudSystem%Op_Kick_Saved_Volume= 0.d0
    data%State%MudSystem%Saved_Op_MudOrKick= 0
    
    
    
    !write(*,*) 'Op_Capacity===' , sum(OpSection_VolumeCapacity(1:F_BottomHoleIntervalCounts))
    !write(*,*) 'Op_MudDischarged_Volume%Length()===' , Op_MudDischarged_Volume%Length()
    !
    
    do imud=1, data%State%MudSystem%Op_MudDischarged_Volume%Length()
        !write(*,*) 'imud, Op_MudDischarged_Volume%Array(imud)=' , imud,Op_MudDischarged_Volume%Array(imud)
        
            data%State%MudSystem%OpMudVolumeSum= data%State%MudSystem%OpMudVolumeSum + data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)
        
        if ( data%State%MudSystem%OpMudVolumeSum > sum(data%State%MudSystem%OpSection_VolumeCapacity(1:data%State%F_Counts%BottomHoleIntervalCounts)) ) then
            
            IF (data%State%MudSystem%Op_MudOrKick%Array(imud) == 0) THEN
                data%State%MudSystem%Op_MudSaved_Density = data%State%MudSystem%Op_Density%Array(imud)
                data%State%MudSystem%Op_Saved_MudDischarged_Volume = data%State%MudSystem%OpMudVolumeSum - sum(data%State%MudSystem%OpSection_VolumeCapacity(1:data%State%F_Counts%BottomHoleIntervalCounts))
            ELSE
                data%State%MudSystem%Op_Kick_Saved_Volume = data%State%MudSystem%OpMudVolumeSum - sum(data%State%MudSystem%OpSection_VolumeCapacity(1:data%State%F_Counts%BottomHoleIntervalCounts))
                !write(*,*) 'cond 1- Op_MudOrKick%Array (imud),Op_Density%Array(imud):' ,Op_MudOrKick%Array (imud),Op_Density%Array(imud)
                data%State%MudSystem%Saved_Op_MudOrKick= data%State%MudSystem%Op_MudOrKick%Array (imud)
                data%State%MudSystem%Op_KickSaved_Density= data%State%MudSystem%Op_Density%Array(imud)
                data%State%MudSystem%iLoc= 2
            END IF
            
            do ii= imud + 1, data%State%MudSystem%Op_MudDischarged_Volume%Length()
                IF (data%State%MudSystem%Op_MudOrKick%Array(ii) == 0) THEN
                    data%State%MudSystem%Op_MudSaved_Density = ((data%State%MudSystem%Op_MudSaved_Density * data%State%MudSystem%Op_Saved_MudDischarged_Volume) + (data%State%MudSystem%Op_Density%Array(ii) * data%State%MudSystem%Op_MudDischarged_Volume%Array(ii))) / (data%State%MudSystem%Op_Saved_MudDischarged_Volume + data%State%MudSystem%Op_MudDischarged_Volume%Array(ii))
                    data%State%MudSystem%Op_Saved_MudDischarged_Volume = data%State%MudSystem%Op_Saved_MudDischarged_Volume + data%State%MudSystem%Op_MudDischarged_Volume%Array(ii)
                ELSE
                    data%State%MudSystem%Op_Kick_Saved_Volume = data%State%MudSystem%Op_Kick_Saved_Volume + data%State%MudSystem%Op_MudDischarged_Volume%Array(ii)
                !write(*,*) 'cond 2- Op_MudOrKick%Array (ii),Op_Density%Array(ii):' ,Op_MudOrKick%Array (ii),Op_Density%Array(ii)
                    data%State%MudSystem%Saved_Op_MudOrKick= data%State%MudSystem%Op_MudOrKick%Array (ii)
                    data%State%MudSystem%Op_KickSaved_Density= data%State%MudSystem%Op_Density%Array(ii)
                    data%State%MudSystem%iLoc= 2
                END IF
            enddo
            
            exit ! exits do
            
        endif
        
    enddo
            !WRITE (*,*) 'Op_Saved_MudDischarged_Volume, Op_Kick_Saved_Volume',Op_Saved_MudDischarged_Volume, Op_Kick_Saved_Volume
!write(*,*) ' iloc (c): ' , iloc
    
!======================================================================   

!======================================================================   
    
        

                
    
    !if (iLoc == 1) then
        data%State%MudSystem%MudSection= data%State%F_Counts%StringIntervalCounts+1
        data%State%MudSystem%BackheadX= data%State%MudSystem%Xstart_PipeSection(data%State%F_Counts%StringIntervalCounts+1)
    !elseif (iLoc == 2) then
    !    MudSection= Kick_Forehead_section
    !    BackheadX= Kick_Forehead_X
    !endif

!========================ANNULUS ENTRANCE====================
    !if (KickMigration_2SideBit == .FALSE.) then     ! because its effect is applied in Migration Code
    !            !write(*,*) 'iloc=====' , iLoc     bejaye data%State%ROP_Bit%RateOfPenetration ==0.   in bude:   DeltaVolumeOp == 0.0
    !    if (ABS(AnnulusSuctionDensity_OldMudSystem%St_Density%Last()) >= DensityMixTol  .OR. (DeltaVolumeOp == 0.0 .and. ABS(Ann_Density%Array(iLoc)data%State%MudSystem%St_Density%Last())>=DensityMixTol .and. data%State%MudSystem%AnnulusFlowRate/=0.0d0) ) then ! new mud is pumped
    !    call Ann_Density%AddTo (iLocMudSystem%St_Density%Last())
    !    call Ann_MudDischarged_Volume%AddTo (iLoc,0.0d0)
    !    call Ann_Mud_Forehead_X%AddTo (iLoc,BackheadX)
    !    call Ann_Mud_Forehead_section%AddTo (iLoc,MudSection)
    !    call Ann_Mud_Backhead_X%AddTo (iLoc,BackheadX)
    !    call Ann_Mud_Backhead_section%AddTo (iLoc,MudSection)
    !    call Ann_RemainedVolume_in_LastSection%AddTo (iLoc,0.0d0)
    !    call Ann_EmptyVolume_inBackheadLocation%AddTo (iLoc,0.0d0)
    !    call Ann_MudOrKick%AddTo (iLoc,0)
    !    call Ann_CuttingMud%AddTo (iLoc,0)
    !            !write(*,*) 'c) annLength=' , Ann_Density%Length()
    !         
    !    AnnulusSuctionDensity_Old=data%State%MudSystem%St_Density%Last()
    !        
    !    MudIsChanged= .true.
    !    endif  
    !
    !            Ann_MudDischarged_Volume%Array(iLoc)= Ann_MudDischarged_Volume%Array(iLoc)+ ((data%State%MudSystem%AnnulusFlowRate/60.d0)*DeltaT_Mudline)    !(gal)
    !
    !endif
    


        
            
        
         data%State%MudSystem%Ann_Mud_Backhead_section%Array(1)= data%State%MudSystem%MudSection !it is needed to be updated for a condition that one pipe is removed from Annulus due to trip out
         data%State%MudSystem%Ann_Mud_Backhead_X%Array(1)= data%State%MudSystem%BackheadX
     
         
         
    !    write(*,*)  'zero)Ann_Mud sum=' , sum(Ann_MudDischarged_Volume%Array(:))  
    !    
    !    
    !write(*,*) 'pump added-before add to ann=='
    !    
    !    do imud=1, Op_MudDischarged_Volume%Length()
    !        write(*,*) 'Op:', imud, Op_MudDischarged_Volume%Array(imud), Op_Density%Array(imud) ,Op_MudOrKick%Array(imud)
    !    enddo             
    !    
    !    do imud=1, Ann_MudDischarged_Volume%Length()
    !        write(*,*) 'Ann:', imud, Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud) ,Ann_MudOrKick%Array(imud)
    !    enddo
    !
    !write(*,*) '====pump added-before add to ann'         
        
        
         
!========================Tripping In==================== 

!write(*,*) 'DeltaVolumeOp=' , DeltaVolumeOp
        if (data%State%ROP_Bit%RateOfPenetration==0.) then    ! .and. Op_MudOrKick%Last() == 0) then      ! trip in mode(loole paeen) Mud
                
                !write(*,*) 'Tripping In'
                !write(*,*) 'before' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)

                !if ( MudIsChanged== .true. ) then
                !    call RemoveAnnulusMudArrays(iLoc) 
                !endif

                
                if (data%State%MudSystem%Op_Kick_Saved_Volume > 0.0 .and. data%State%MudSystem%Ann_MudOrKick%First() == 0) then
                    write(*,*) 'Kick influx enters Annulus'
                    call data%State%MudSystem%Ann_Density%AddToFirst (data%State%MudSystem%Op_KickSaved_Density)
                    call data%State%MudSystem%Ann_MudDischarged_Volume%AddToFirst (data%State%MudSystem%Op_Kick_Saved_Volume)
                    call data%State%MudSystem%Ann_Mud_Forehead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(data%State%F_Counts%StringIntervalCounts+1))
                    call data%State%MudSystem%Ann_Mud_Forehead_section%AddToFirst (data%State%F_Counts%StringIntervalCounts+1)
                    call data%State%MudSystem%Ann_Mud_Backhead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(data%State%F_Counts%StringIntervalCounts+1))
                    call data%State%MudSystem%Ann_Mud_Backhead_section%AddToFirst (data%State%F_Counts%StringIntervalCounts+1)
                    call data%State%MudSystem%Ann_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                    call data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0) 
                    call data%State%MudSystem%Ann_MudOrKick%AddToFirst (data%State%MudSystem%Saved_Op_MudOrKick)      !<<<<<<<<
                    call data%State%MudSystem%Ann_CuttingMud%AddToFirst (0)
                elseif (data%State%MudSystem%Op_Kick_Saved_Volume > 0.0 .and. data%State%MudSystem%Ann_MudOrKick%First() /= 0) then
                    data%State%MudSystem%Ann_MudDischarged_Volume%Array(1)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(1) + data%State%MudSystem%Op_Kick_Saved_Volume
                endif
                
                
            if (data%State%MudSystem%Op_Saved_MudDischarged_Volume> 0.0) then
                data%State%MudSystem%NewDensity= data%State%MudSystem%Op_MudSaved_Density
                data%State%MudSystem%NewVolume= data%State%MudSystem%Op_Saved_MudDischarged_Volume
                !write(*,*) 'NewVolume=' , NewVolume
                !write(*,*) 'iloc=' , iloc,'Ann_MudDischarged_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                

                
                if ((data%State%ROP_Bit%RateOfPenetration==0 .and. abs(data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)-data%State%MudSystem%NewDensity)< data%State%MudSystem%DensityMixTol) &
                .or. (data%State%ROP_Bit%RateOfPenetration>0. .and. data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==1 .and. abs(data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)-data%State%MudSystem%NewDensity)< data%State%MudSystem%CuttingDensityMixTol) &
                .or. (data%State%ROP_Bit%RateOfPenetration>0. .and. data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==0 .and. data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc) < 42.) ) then   ! 1-Pockets are Merged
                 
                    data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)= (data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)*data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewDensity*data%State%MudSystem%NewVolume)/(data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume)
                    data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume
                    data%State%MudSystem%Ann_Mud_Forehead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                    data%State%MudSystem%Ann_Mud_Forehead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                    data%State%MudSystem%Ann_Mud_Backhead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                    data%State%MudSystem%Ann_Mud_Backhead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                    data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(data%State%MudSystem%iLoc)= (0.0d0)
                    data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(data%State%MudSystem%iLoc)= (0.0d0) 
                !write(*,*) 'merge' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                    
                else       ! 2-Merging conditions are not meeted, so new pocket
                    call data%State%MudSystem%Ann_Density%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewDensity)
                    call data%State%MudSystem%Ann_MudDischarged_Volume%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewVolume)
                    call data%State%MudSystem%Ann_Mud_Forehead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Forehead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_Mud_Backhead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Backhead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_RemainedVolume_in_LastSection%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_MudOrKick%AddTo (data%State%MudSystem%iLoc,0)
                    call data%State%MudSystem%Ann_CuttingMud%AddTo (data%State%MudSystem%iLoc,0)
                    !write(*,*) 'd) annLength=' , Ann_Density%Length()
                !write(*,*) 'new' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                
                endif
            endif
     
        endif   
             
!========================Tripping In - End==================== 
            
!========================Drilling Mode========================            
            
        if (data%State%ROP_Bit%RateOfPenetration>0. .and. data%State%MudSystem%DeltaVolumeOp>0.0) then      ! trip in mode(loole paeen)   DrillingMode== .true.
            !write(*,*) 'Drilling Mode'
        
                !if ( MudIsChanged== .true. ) then
                !    call RemoveAnnulusMudArrays(iLoc) 
                !endif                
                !write(*,*) 'before' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                
                
                !data%State%MudSystem%NewDensity= data%State%MudSystem%St_Density%Last() * data%State%MudSystem%AnnulusFlowRate + 141.4296E-4*data%State%ROP_Bit%RateOfPenetration*data%State%ROP_Spec%DiameterOfBit**2)/(data%State%MudSystem%AnnulusFlowRate+6.7995E-4*data%State%ROP_Bit%RateOfPenetration*Diameter_of_Bit**2)
                
                data%State%MudSystem%NewDensity=data%State%MudSystem%St_Density%Last()
                
                
                !NewVolume= ((data%State%MudSystem%AnnulusFlowRate/60.0d0)*DeltaT_Mudline)+DeltaVolumeOp
                !!! Density in ppg, flow rate in gpm, ROP in ft/s, bit diameter in inch         

                
                do imud=1, data%State%MudSystem%Op_MudDischarged_Volume%Length()
                    if ( data%State%MudSystem%Op_MudOrKick%Array(imud) == 0 ) then
                        data%State%MudSystem%Op_Density%Array(imud)= data%State%MudSystem%NewDensity
                        
                    endif
                enddo
                
                
                
                if (data%State%MudSystem%Op_Kick_Saved_Volume > 0.0 .and. data%State%MudSystem%Ann_MudOrKick%First() == 0) then
                    write(*,*) 'Kick influx enters Annulus first time'
                    !write(*,*) 'Saved_Op_MudOrKick=',Saved_Op_MudOrKick
                    call data%State%MudSystem%Ann_Density%AddToFirst (data%State%MudSystem%Op_KickSaved_Density)
                    call data%State%MudSystem%Ann_MudDischarged_Volume%AddToFirst (data%State%MudSystem%Op_Kick_Saved_Volume)
                    call data%State%MudSystem%Ann_Mud_Forehead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(data%State%F_Counts%StringIntervalCounts+1))
                    call data%State%MudSystem%Ann_Mud_Forehead_section%AddToFirst (data%State%F_Counts%StringIntervalCounts+1)
                    call data%State%MudSystem%Ann_Mud_Backhead_X%AddToFirst (data%State%MudSystem%Xstart_PipeSection(data%State%F_Counts%StringIntervalCounts+1))
                    call data%State%MudSystem%Ann_Mud_Backhead_section%AddToFirst (data%State%F_Counts%StringIntervalCounts+1)
                    call data%State%MudSystem%Ann_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                    call data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0) 
                    call data%State%MudSystem%Ann_MudOrKick%AddToFirst (data%State%MudSystem%Saved_Op_MudOrKick)      !<<<<<<<<
                    call data%State%MudSystem%Ann_CuttingMud%AddToFirst (0)
                elseif (data%State%MudSystem%Op_Kick_Saved_Volume > 0.0 .and. data%State%MudSystem%Ann_MudOrKick%First() /= 0) then
                    data%State%MudSystem%Ann_MudDischarged_Volume%Array(1)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(1) + data%State%MudSystem%Op_Kick_Saved_Volume
                endif
                
                
            if (data%State%MudSystem%Op_Saved_MudDischarged_Volume> 0.0) then
                !write(*,*) 'Op_Saved_Mud added'
                data%State%MudSystem%NewDensity= data%State%MudSystem%NewDensity  !(drilling density)
                data%State%MudSystem%NewVolume= data%State%MudSystem%Op_Saved_MudDischarged_Volume + data%State%MudSystem%DeltaVolumeOp        ! (DeltaVolumeOp: for Cuttings Volume)
                !write(*,*) 'NewVolume=' , NewVolume
                !write(*,*) 'iloc=' , iloc,'Ann_MudDischarged_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                
                 if ( (data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==1 .and. abs(data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)-data%State%MudSystem%NewDensity)< data%State%MudSystem%CuttingDensityMixTol ) &  
                    .or. (data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==0 .and. data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc) < 42.) ) then   ! 1-Pockets are Merged
                                  
                     data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)= (data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)*data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewDensity*data%State%MudSystem%NewVolume)/(data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume)
                     data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume
                     data%State%MudSystem%Ann_Mud_Forehead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                     data%State%MudSystem%Ann_Mud_Forehead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                     data%State%MudSystem%Ann_Mud_Backhead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                     data%State%MudSystem%Ann_Mud_Backhead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                     data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(data%State%MudSystem%iLoc)= (0.0d0)
                     data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(data%State%MudSystem%iLoc)= (0.0d0) 
                     data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)= 1
                !write(*,*) 'merge' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                     
                 else        ! 2-Merging conditions are not meeted, so new pocket
                    !write(*,*) 'before e) ', iloc, Ann_Density%Array(iLoc),data%State%MudSystem%NewDensity
                    !write(*,*) 'before e) Ann_MudDischarged_Volume%Array(iLoc)=' , Ann_MudDischarged_Volume%Array(iLoc)
                
                 
                    call data%State%MudSystem%Ann_Density%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewDensity)
                    call data%State%MudSystem%Ann_MudDischarged_Volume%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewVolume)
                    call data%State%MudSystem%Ann_Mud_Forehead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Forehead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_Mud_Backhead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Backhead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_RemainedVolume_in_LastSection%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_MudOrKick%AddTo (data%State%MudSystem%iLoc,0)
                    call data%State%MudSystem%Ann_CuttingMud%AddTo (data%State%MudSystem%iLoc,1)  ! 1= cutting  0= mud
                !write(*,*) 'new' ,'Ann_Volume%Array(1)=' , Ann_MudDischarged_Volume%Array(1)
                    
                    !write(*,*) 'e) annLength=' , Ann_Density%Length()
                
                
            endif 
                

            endif                

        endif  
!===================================================================         

    !write(*,*) 'after add to ann=='
    !    
    !    do imud=1, Op_MudDischarged_Volume%Length()
    !        write(*,*) 'Op:', imud, Op_MudDischarged_Volume%Array(imud), Op_Density%Array(imud) ,Op_MudOrKick%Array(imud)
    !    enddo             
    !    
    !    do imud=1, Ann_MudDischarged_Volume%Length()
    !        write(*,*) 'Ann:', imud, Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud) ,Ann_MudOrKick%Array(imud)
    !    enddo
    !
    !write(*,*) '==after add to ann'  
        
                    data%State%MudSystem%NewVolume= ((data%State%MudSystem%AnnulusFlowRate/60.d0)*data%State%MudSystem%DeltaT_Mudline) - data%State%MudSystem%Op_Saved_MudDischarged_Volume

                if (data%State%MudSystem%iLoc==2 .and. data%State%MudSystem%Op_MudOrKick%Last()==0 .and. data%State%MudSystem%NewVolume > 0.d0 ) then                    ! for avoid kick separation
                    !write(*,*) 'avoid kick separation'

                    
                    data%State%MudSystem%NewDensity= data%State%MudSystem%Op_MudSaved_Density
                    
                    call RemoveOpMudArrays(data%State%MudSystem%Op_Density%Length()) ! mud here is removed and then will be added to iloc=2 in Ann
                    if ( data%State%MudSystem%Ann_MudDischarged_Volume%Array(1) > ((data%State%MudSystem%AnnulusFlowRate/60.d0)*data%State%MudSystem%DeltaT_Mudline)- data%State%MudSystem%Op_Saved_MudDischarged_Volume) then! 1st in Ann = kick
                        !write(*,*) 'mode1'
                        data%State%MudSystem%Ann_MudDischarged_Volume%Array(1)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(1) - (((data%State%MudSystem%AnnulusFlowRate/60.d0)*data%State%MudSystem%DeltaT_Mudline) -data%State%MudSystem%Op_Saved_MudDischarged_Volume)
                        data%State%MudSystem%Op_MudDischarged_Volume%Array(data%State%MudSystem%Op_Density%Length())= data%State%MudSystem%Op_MudDischarged_Volume%Array(data%State%MudSystem%Op_Density%Length())+ (((data%State%MudSystem%AnnulusFlowRate/60.d0)*data%State%MudSystem%DeltaT_Mudline) - data%State%MudSystem%Op_Saved_MudDischarged_Volume)  !kick
                    else
                        call RemoveAnnulusMudArrays(1)  !kick is removed
                        data%State%MudSystem%iLoc= 1
                        data%State%MudSystem%Op_MudDischarged_Volume%Array(data%State%MudSystem%Op_Density%Length())= data%State%MudSystem%Op_MudDischarged_Volume%Array(data%State%MudSystem%Op_Density%Length())+ (((data%State%MudSystem%AnnulusFlowRate/60.d0)*data%State%MudSystem%DeltaT_Mudline) - data%State%MudSystem%Op_Saved_MudDischarged_Volume)
                        !write(*,*) 'mode2'

                        ! including  a little expand
                    endif

                
                if ((data%State%ROP_Bit%RateOfPenetration==0 .and. abs(data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)-data%State%MudSystem%NewDensity)< data%State%MudSystem%DensityMixTol) &
                .or. (data%State%ROP_Bit%RateOfPenetration>0. .and. data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==1 .and. abs(data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)-data%State%MudSystem%NewDensity)< data%State%MudSystem%CuttingDensityMixTol) &
                .or. (data%State%ROP_Bit%RateOfPenetration>0. .and. data%State%MudSystem%Ann_CuttingMud%Array(data%State%MudSystem%iLoc)==0 .and. data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc) < 42.) ) then   ! 1-Pockets are Merged
                 
                    data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)= (data%State%MudSystem%Ann_Density%Array(data%State%MudSystem%iLoc)*data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewDensity*data%State%MudSystem%NewVolume)/(data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume)
                    data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(data%State%MudSystem%iLoc)+data%State%MudSystem%NewVolume
                    data%State%MudSystem%Ann_Mud_Forehead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                    data%State%MudSystem%Ann_Mud_Forehead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                    data%State%MudSystem%Ann_Mud_Backhead_X%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%BackheadX
                    data%State%MudSystem%Ann_Mud_Backhead_section%Array(data%State%MudSystem%iLoc)= data%State%MudSystem%MudSection
                    data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(data%State%MudSystem%iLoc)= (0.0d0)
                    data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(data%State%MudSystem%iLoc)= (0.0d0)                    
                else       ! 2-Merging conditions are not meeted, so new pocket
                    call data%State%MudSystem%Ann_Density%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewDensity)
                    call data%State%MudSystem%Ann_MudDischarged_Volume%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%NewVolume)
                    call data%State%MudSystem%Ann_Mud_Forehead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Forehead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_Mud_Backhead_X%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%BackheadX)
                    call data%State%MudSystem%Ann_Mud_Backhead_section%AddTo (data%State%MudSystem%iLoc,data%State%MudSystem%MudSection)
                    call data%State%MudSystem%Ann_RemainedVolume_in_LastSection%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%AddTo (data%State%MudSystem%iLoc,0.0d0)
                    call data%State%MudSystem%Ann_MudOrKick%AddTo (data%State%MudSystem%iLoc,0)
                    call data%State%MudSystem%Ann_CuttingMud%AddTo (data%State%MudSystem%iLoc,0)
                    !write(*,*) 'd) annLength=' , Ann_Density%Length()
                
                endif
                    

                endif        
!=================================================================== 
         if( data%State%MudSystem%Op_MudOrKick%Last() == 1 .and. data%State%MudSystem%Ann_MudOrKick%First() == 0 ) then
             
        write(*,*) '***error2****=='
        
        write(*,*) 'Op_Kick_Saved_Volume,Op_Saved_MudDischarged_Volume=' , data%State%MudSystem%Op_Kick_Saved_Volume,data%State%MudSystem%Op_Saved_MudDischarged_Volume
        

    write(*,*) 'after add to ann=='
        
        do imud=1, data%State%MudSystem%Op_MudDischarged_Volume%Length()
            write(*,*) 'Op:', imud, data%State%MudSystem%Op_MudDischarged_Volume%Array(imud), data%State%MudSystem%Op_Density%Array(imud) ,data%State%MudSystem%Op_MudOrKick%Array(imud)
        enddo             
        
        do imud=1, data%State%MudSystem%Ann_MudDischarged_Volume%Length()
            write(*,*) 'Ann:', imud, data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud), data%State%MudSystem%Ann_Density%Array(imud) ,data%State%MudSystem%Ann_MudOrKick%Array(imud)
        enddo
    
    write(*,*) '==after add to ann'  
                            
        write(*,*) 'NewVolume,Op_MudOrKick%Last=' , data%State%MudSystem%NewVolume,data%State%MudSystem%Op_MudOrKick%Last()
        write(*,*) '==***error2****'
        
        endif
                
                
                
                
                
!=============== save Ann Mud data to transfer to the ChokeLine enterance 
    data%State%MudSystem%AnnMudVolumeSum= 0.d0
    !Ann_MudSaved_Density= 0.d0
    !Ann_KickSaved_Density= 0.d0
    data%State%MudSystem%Ann_Saved_MudDischarged_Volume= 0.d0
    data%State%MudSystem%Ann_Kick_Saved_Volume= 0.d0
    data%State%MudSystem%Saved_Ann_MudOrKick= 0
    data%State%MudSystem%Ann_to_Choke_2mud= .false.
    
    
    
    
    do imud=1, data%State%MudSystem%Ann_MudDischarged_Volume%Length()
        
            data%State%MudSystem%AnnMudVolumeSum= data%State%MudSystem%AnnMudVolumeSum + data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)
        
        if ( data%State%MudSystem%AnnMudVolumeSum > sum(data%State%MudSystem%PipeSection_VolumeCapacity(data%State%F_Counts%StringIntervalCounts+1:data%State%MudSystem%NoPipeSections)) ) then
            
            IF (data%State%MudSystem%Ann_MudOrKick%Array(imud) == 0) THEN
                data%State%MudSystem%Ann_MudSaved_Density = data%State%MudSystem%Ann_Density%Array(imud)
                data%State%MudSystem%Ann_Saved_MudDischarged_Volume = data%State%MudSystem%AnnMudVolumeSum - sum(data%State%MudSystem%PipeSection_VolumeCapacity(data%State%F_Counts%StringIntervalCounts+1:data%State%MudSystem%NoPipeSections))
            ELSEIF (data%State%MudSystem%Ann_MudOrKick%Array(imud) > 0 .AND. data%State%MudSystem%Ann_MudOrKick%Array(imud) <100) THEN        ! 104= AIR
                data%State%MudSystem%Ann_Kick_Saved_Volume = data%State%MudSystem%AnnMudVolumeSum - sum(data%State%MudSystem%PipeSection_VolumeCapacity(data%State%F_Counts%StringIntervalCounts+1:data%State%MudSystem%NoPipeSections))
                data%State%MudSystem%Saved_Ann_MudOrKick= data%State%MudSystem%Ann_MudOrKick%Array (imud)
                data%State%MudSystem%Ann_KickSaved_Density= data%State%MudSystem%Ann_Density%Array(imud)
            END IF
            
            do ii= imud + 1, data%State%MudSystem%Ann_MudDischarged_Volume%Length()
                IF (data%State%MudSystem%Ann_MudOrKick%Array(ii) == 0) THEN
                    data%State%MudSystem%Ann_MudSaved_Density = ((data%State%MudSystem%Ann_MudSaved_Density * data%State%MudSystem%Ann_Saved_MudDischarged_Volume) + (data%State%MudSystem%Ann_Density%Array(ii) * data%State%MudSystem%Ann_MudDischarged_Volume%Array(ii))) / (data%State%MudSystem%Ann_Saved_MudDischarged_Volume + data%State%MudSystem%Ann_MudDischarged_Volume%Array(ii))
                    data%State%MudSystem%Ann_Saved_MudDischarged_Volume = data%State%MudSystem%Ann_Saved_MudDischarged_Volume + data%State%MudSystem%Ann_MudDischarged_Volume%Array(ii)
                    data%State%MudSystem%Ann_to_Choke_2mud= .true.
                ELSEIF (data%State%MudSystem%Ann_MudOrKick%Array(ii) > 0 .AND. data%State%MudSystem%Ann_MudOrKick%Array(ii) <100) THEN        ! 104= AIR
                    data%State%MudSystem%Ann_Kick_Saved_Volume = data%State%MudSystem%Ann_Kick_Saved_Volume + data%State%MudSystem%Ann_MudDischarged_Volume%Array(ii)
                    data%State%MudSystem%Saved_Ann_MudOrKick= data%State%MudSystem%Ann_MudOrKick%Array (ii)
                    data%State%MudSystem%Ann_KickSaved_Density= data%State%MudSystem%Ann_Density%Array(ii)
                END IF
            enddo
            
            
            !WRITE (*,*) 'Ann_Saved_Mud_Volume, Ann_Kick_Saved_Volume', Ann_Saved_MudDischarged_Volume, Ann_Kick_Saved_Volume
            exit
            
        endif
        
    enddo
data%State%MudSystem%Ann_Saved_MudDischarged_Volume_Final= data%State%MudSystem%Ann_Saved_MudDischarged_Volume !+ Ann_Kick_Saved_Volume
data%State%MudSystem%Ann_Kick_Saved_Volume_Final= data%State%MudSystem%Ann_Kick_Saved_Volume
IF (data%State%MudSystem%WellHeadIsOpen)       data%State%MudSystem%MudVolume_InjectedFromAnn = data%State%MudSystem%Ann_Saved_MudDischarged_Volume_Final -((data%State%MudSystem%Qlost/60.0d0)*data%State%MudSystem%DeltaT_Mudline)
!WRITE (*,*) 'data%State%MudSystem%MudVolume_InjectedFromAnn=', data%State%MudSystem%MudVolume_InjectedFromAnn
!======================================================================                  
                
        !write(*,*)  'c)Ann_Mud sum=' , sum(Ann_MudDischarged_Volume%Array(:)) 
        !write(*,*) 'Ann cap=' , sum(PipeSection_VolumeCapacity(F_StringIntervalCounts+1:NoPipeSections))
        !write(*,*)  'Ann_Saved_Mud=' , Ann_Saved_MudDischarged_Volume
        
        data%State%MudSystem%total_injected = data%State%MudSystem%total_injected + data%State%MudSystem%MudVolume_InjectedFromAnn
        
                    if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
                        data%State%MudSystem%total_injected= 0.
                    endif        
        
        !write(*,*) ' total injected-tripin =' , total_injected
        !write(*,*) 'injected-tripin =' , data%State%MudSystem%MudVolume_InjectedFromAnn
        
        
        
     
                
!======================== Annulus ==================== 
             
                   !MudIsChanged= .false.          
                
imud= 0

    do while (imud < data%State%MudSystem%Ann_Mud_Forehead_X%Length())
        imud = imud + 1
        
            if (imud> 1) then
                data%State%MudSystem%Ann_Mud_Backhead_X%Array(imud)= data%State%MudSystem%Ann_Mud_Forehead_X%Array(imud-1)
                data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud)= data%State%MudSystem%Ann_Mud_Forehead_section%Array(imud-1)
            endif
           

            
!       <<< Fracture Shoe Lost            
            IF ( data%State%MudSystem%ShoeLost .and. Shoe%ShoeDepth < data%State%MudSystem%Ann_Mud_Backhead_X%Array(imud) .and. Shoe%ShoeDepth >= data%State%MudSystem%Ann_Mud_Forehead_X%Array(imud) ) then
                !write(*,*) 'ShoeLost   imud,AnnVolume(imud), VolumeLost:' , imud,Ann_MudDischarged_Volume%Array(imud), (( Qlost/60.0d0)*DeltaT_Mudline)
                data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)-((data%State%MudSystem%Qlost/60.0d0)*data%State%MudSystem%DeltaT_Mudline)    !(gal)
                if (data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud) < 0.0) then
                    !write(*,*) 'mud is removed by shoe lost, imud=' , imud
                    call RemoveAnnulusMudArrays(imud)
                    imud= imud-1
                    cycle
                endif
                
            ENDIF
!           Fracture Shoe Lost >>>        
            
            
            data%State%MudSystem%DirectionCoef= (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud))) &
                / ABS(data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud)))
            ! +1 for string  ,   -1 for annulus
                
                                                                                                                    
            data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%DirectionCoef* (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud))- data%State%MudSystem%Ann_Mud_Backhead_X%Array(imud))* &
                data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud)) !(ft^3)          
            data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(imud)* 7.48051948d0        ! ft^3  to gal
            
         
            if ( data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud) <= data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(imud)) then
                data%State%MudSystem%Ann_Mud_Forehead_section%Array(imud)= data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud)
                data%State%MudSystem%Ann_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Ann_Mud_Backhead_X%Array(imud)+ data%State%MudSystem%DirectionCoef*(data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)/7.48051948d0)/data%State%MudSystem%Area_PipeSectionFt(data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud))
                                                                            !   7.48 is for gal to ft^3
                
            else
                    
                data%State%MudSystem%isection= data%State%MudSystem%Ann_Mud_Backhead_section%Array(imud)+1
                data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Ann_EmptyVolume_inBackheadLocation%Array(imud)
                    
                do 
                        if (data%State%MudSystem%isection > data%State%MudSystem%NoPipeSections) then        ! last pipe section(well exit)
                            data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)= data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(imud)
                            data%State%MudSystem%Ann_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%NoPipeSections)
                            data%State%MudSystem%Ann_Mud_Forehead_section%Array(imud)= data%State%MudSystem%NoPipeSections
                                
                            if (data%State%MudSystem%Ann_MudDischarged_Volume%Array(imud)<= 0.0d0)  then      ! imud is completely exited form the well
                                !write(*,*) 'remove******'
                                call RemoveAnnulusMudArrays(imud)
                            endif
                            exit
                        endif
                                 
                    data%State%MudSystem%xx= data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(imud)/ data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)   !(gal)
                        
                    if (data%State%MudSystem%xx<= 1.0) then
                        data%State%MudSystem%Ann_Mud_Forehead_section%Array(imud)= data%State%MudSystem%isection
                        data%State%MudSystem%Ann_Mud_Forehead_X%Array(imud)= (data%State%MudSystem%xx * (data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%isection)- data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)))+ data%State%MudSystem%Xstart_PipeSection(data%State%MudSystem%isection)
                        exit
                    else
                        data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Ann_RemainedVolume_in_LastSection%Array(imud)- data%State%MudSystem%PipeSection_VolumeCapacity(data%State%MudSystem%isection)
                        data%State%MudSystem%isection= data%State%MudSystem%isection+ 1
                                
                    endif

                enddo
            
            endif   
!            write(*,*) 'imud=' , imud
!write(*,*) 'Pinter4 **Ann_Length()=' , Ann_Mud_Forehead_X%Length()
!            write(*,*) 'Ann_Density%Array (imud)=' , Ann_Density%Array (imud)
!
!            
!write(*,*) imud,'Ann_Mud_Forehead_X%Array(imud)=' , Ann_Mud_Forehead_X%Array(imud)

            !if (Ann_Mud_Forehead_X%Array(imud) < Xend_PipeSection(NoPipeSections)) then
            !    Ann_Mud_Forehead_X%Array(imud) = Xend_PipeSection(NoPipeSections)       ! for error preventing
            !endif
            
    !write(*,*) imud, 'Ann_MudDischarged_Volume%Array(imud)=' , Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud)
    

    enddo
    
            if (data%State%MudSystem%Ann_Mud_Forehead_X%Last() < data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%NoPipeSections)) then
                data%State%MudSystem%Ann_Mud_Forehead_X%Array(data%State%MudSystem%Ann_Mud_Forehead_X%Length()) = data%State%MudSystem%Xend_PipeSection(data%State%MudSystem%NoPipeSections)       ! for error preventing
            endif
    
!========================ANNULUS END================= 
    !write(*,*) 'sum(Ann_MudDischarged_Volume%Array())=' , sum(Ann_MudDischarged_Volume%Array(:))

!========================================================= 
            
            
    !write(*,*) 'before======2' 
    !
    !    do imud=1, Op_MudDischarged_Volume%Length()
    !        write(*,*) 'Op:', imud, Op_MudDischarged_Volume%Array(imud), Op_Density%Array(imud) ,Op_MudOrKick%Array(imud)
    !    enddo
    !write(*,*) '2======before'  

            
!========================Bottom Hole=================                     
imud=0                     
    do while (imud < data%State%MudSystem%Op_Mud_Forehead_X%Length())
        imud = imud + 1
        
            if (imud> 1) then
                data%State%MudSystem%Op_Mud_Backhead_X%Array(imud)= data%State%MudSystem%Op_Mud_Forehead_X%Array(imud-1)
                data%State%MudSystem%Op_Mud_Backhead_section%Array(imud)= data%State%MudSystem%Op_Mud_Forehead_section%Array(imud-1)
            endif
            !write(*,*) 'imud**=' , imud
            data%State%MudSystem%DirectionCoef= (data%State%MudSystem%Xend_OpSection(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_OpSection(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud))) &
                / ABS(data%State%MudSystem%Xend_OpSection(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud))-data%State%MudSystem%Xstart_OpSection(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud)))
            ! +1 for string  ,   -1 for annulus
                                           
                                                                                                                    
            data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%DirectionCoef* (data%State%MudSystem%Xend_OpSection(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud))- data%State%MudSystem%Op_Mud_Backhead_X%Array(imud))* &
                data%State%MudSystem%Area_OpSectionFt(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud)) !(ft^3)          
            data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(imud)* 7.48051948d0        ! ft^3  to gal
                !write(*,*)  ' Op_EmptyVolume_inBackheadLocation%Array(1) =' , Op_EmptyVolume_inBackheadLocation%Array(1) 
                if ( data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(1) < 0.0)      CALL ErrorStop1 ('Negative Empty volume')
            
            if ( data%State%MudSystem%Op_MudDischarged_Volume%Array(imud) <= data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(imud)) then
                data%State%MudSystem%Op_Mud_Forehead_section%Array(imud)= data%State%MudSystem%Op_Mud_Backhead_section%Array(imud)
                data%State%MudSystem%Op_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Op_Mud_Backhead_X%Array(imud)+ data%State%MudSystem%DirectionCoef*(data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)/7.48051948d0)/data%State%MudSystem%Area_OpSectionFt(data%State%MudSystem%Op_Mud_Backhead_section%Array(imud))
                                                                            !   7.48 is for gal to ft^3
                
            else
                
                    
                data%State%MudSystem%isection= data%State%MudSystem%Op_Mud_Backhead_section%Array(imud)+1
                data%State%MudSystem%Op_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Op_EmptyVolume_inBackheadLocation%Array(imud)
                    
                do 
                        if (data%State%MudSystem%isection > data%State%F_Counts%BottomHoleIntervalCounts) then        ! last pipe section(well exit)
                            !if( imud==1) KickDeltaVinAnnulus= Op_RemainedVolume_in_LastSection%Array(imud)      ! Kick enters Annulus space
                            data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)= data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)- data%State%MudSystem%Op_RemainedVolume_in_LastSection%Array(imud)
                            data%State%MudSystem%Op_Mud_Forehead_X%Array(imud)= data%State%MudSystem%Xend_OpSection(data%State%F_Counts%BottomHoleIntervalCounts)
                            data%State%MudSystem%Op_Mud_Forehead_section%Array(imud)= data%State%F_Counts%BottomHoleIntervalCounts
                                
                            if (data%State%MudSystem%Op_MudDischarged_Volume%Array(imud)<= 0.0d0)  then        ! imud is completely exited form the well
                                call RemoveOpMudArrays(imud)
                            endif
                            
                            exit
                        endif
                                 
                    data%State%MudSystem%xx= data%State%MudSystem%Op_RemainedVolume_in_LastSection%Array(imud)/ data%State%MudSystem%OpSection_VolumeCapacity(data%State%MudSystem%isection)   !(gal)
                        
                    if (data%State%MudSystem%xx<= 1.0) then
                        data%State%MudSystem%Op_Mud_Forehead_section%Array(imud)= data%State%MudSystem%isection
                        data%State%MudSystem%Op_Mud_Forehead_X%Array(imud)= (data%State%MudSystem%xx * (data%State%MudSystem%Xend_OpSection(data%State%MudSystem%isection)- data%State%MudSystem%Xstart_OpSection(data%State%MudSystem%isection)))+ data%State%MudSystem%Xstart_OpSection(data%State%MudSystem%isection)
                        exit
                    else
                        data%State%MudSystem%Op_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%Op_RemainedVolume_in_LastSection%Array(imud)- data%State%MudSystem%OpSection_VolumeCapacity(data%State%MudSystem%isection)
                        data%State%MudSystem%isection= data%State%MudSystem%isection+ 1
                        
                    endif

                enddo
            
            endif  
!       for OP remove:
       
        if (data%State%MudSystem%Op_Mud_Forehead_X%Array(imud)== data%State%MudSystem%Xend_OpSection(data%State%F_Counts%BottomHoleIntervalCounts)) then
            data%State%MudSystem%totalLength = data%State%MudSystem%Op_MudDischarged_Volume%Length()
            do while(imud < data%State%MudSystem%totalLength)
                
                !imud = imud + 1
                call RemoveOpMudArrays(data%State%MudSystem%totalLength)
                data%State%MudSystem%totalLength = data%State%MudSystem%totalLength - 1

                
            enddo
            
            exit ! 
            
        endif       
       
       
       
       
        !if (Op_Mud_Forehead_X%Array(imud)== Xend_OpSection(data%State%F_Counts%BottomHoleIntervalCounts)) then
        !    totalLength = Op_MudDischarged_Volume%Length()
        !    do while(imud <= totalLength)
        !        
        !        imud = imud + 1
        !        call RemoveOpMudArrays(imud)
        !        totalLength = totalLength - 1
        !
        !        
        !    enddo
        !    
        !    exit ! 
        !    
        !endif            
  
    enddo
 
       !write(*,*) 'OpSection_VolumeCapacity sum=' , sum(OpSection_VolumeCapacity(:))
       


!========================Bottom Hole END=================             
            
            
    !write(*,*) 'after sorting=='
    !    
    !    do imud=1, Op_MudDischarged_Volume%Length()
    !        write(*,*) 'Op:', imud, Op_MudDischarged_Volume%Array(imud), Op_Density%Array(imud) ,Op_MudOrKick%Array(imud)
    !    enddo             
    !    
    !    do imud=1, Ann_MudDischarged_Volume%Length()
    !        write(*,*) 'Ann:', imud, Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud) ,Ann_MudOrKick%Array(imud)
    !    enddo
    !    
    !    !
    !    !do imud=1, st_MudDischarged_Volume%Length()
    !    !    write(*,*) 'st:', imud, St_MudDischarged_Volume%Array(imud), St_Mud_Backhead_X%Array(imud) ,St_Mud_Forehead_X%Array(imud)
    !    !enddo        
    !
    !write(*,*) '==after sorting'             
     
    
    !    write(*,*) 'after sorting st=='
    !
    !     do imud=1, st_MudDischarged_Volume%Length()
    !        write(*,*) 'st-plot:', imud, St_MudDischarged_Volume%Array(imud), St_Mud_Backhead_X%Array(imud) ,St_Mud_Forehead_X%Array(imud)data%State%MudSystem%St_Density%Array(imud)
    !    enddo  
    !
    !write(*,*) '==after sorting st'    
    
    
    
                       
    !write(*,*) '**Ann_Kick_Saved_Final,Mud_InjectedFromAnn' , Ann_Kick_Saved_Volume_Final,data%State%MudSystem%MudVolume_InjectedFromAnn              

    end subroutine Pump_and_TripIn
    
    

    
    
    
    
    
    
    
    
 subroutine ChokeLineMud    !  is called in subroutine CirculationCodeSelect
    
        Use GeoElements_FluidModule
        USE CMudPropertiesVariables
        USE MudSystemVARIABLES
use SimulationVariables !@@@
        use SimulationVariables
        USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !use CDataDisplayConsole
   !@ use ConfigurationVariables ,  StandPipePressureDataDisplay=>StandPipePressure
        !use CManifolds
        use SimulationVariables !@
        USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !use CChokeManifoldVariables
    use SimulationVariables
        !use CTanks
    !@use ConfigurationVariables, TripTankVolume2 => data%EquipmentControl%DrillingWatch%TripTankVolume, TripTankDensity2 => TripTankDensity
        USE sROP_Other_Variables
        USE sROP_Variables
        use KickVARIABLESModule
        use PressureDisplayVARIABLESModule
        Use CError
        Use , intrinsic :: IEEE_Arithmetic
        
   
   implicit none
   
   integer i,ii,error_occured
   
   error_occured = 0
   

   
   
       !write(*,*) 'begining chokeline=='
        !write(*,*) 'Ann last:', Ann_MudDischarged_Volume%Last(), Ann_Density%Last() ,Ann_MudOrKick%Last()
        !
        !do imud=1, ChokeLine_MudDischarged_Volume%Length()
       !     write(*,*) 'ChokeLine:', imud, ChokeLine_MudDischarged_Volume%Array(imud), ChokeLine_Density%Array(imud) ,ChokeLine_MudOrKick%Array(imud)
        !enddo             
        
    
    
    !write(*,*) 'Ann_Kick_Saved_Volume_Final,data%State%MudSystem%MudVolume_InjectedFromAnn' , Ann_Kick_Saved_Volume_Final,data%State%MudSystem%MudVolume_InjectedFromAnn  
    
       !write(*,*) 'begining chokeline=='
   
   
   
   
   
   
   
        data%State%MudSystem%ChokeLineFlowRate = data%State%MUD(4)%Q
        !WRITE (*,*) 'data%State%MUD(4)%Q', data%State%MUD(4)%Q
   
   
        if (data%State%MudSystem%NewPipeFilling == 0) then   ! .or. UtubeFilling==0) then
            data%State%MudSystem%ChokeLineFlowRate= 0.
        endif  
        
        
        do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()-2
            if ( data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) ==1 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+1) ==0 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+2) ==1 ) then
                write(*,*) 'error_location is 1'
                error_occured = 1
            endif          
        enddo             
        

        
        !
        !do imud=1, st_MudDischarged_Volume%Length()
        !    write(*,*) 'st:', imud, St_MudDischarged_Volume%Array(imud), St_Mud_Backhead_X%Array(imud) ,St_Mud_Forehead_X%Array(imud)
        !enddo 
        

 !========================CHOKE LINE ENTRANCE================= 

        !if ( Ann_Kick_Saved_Volume > 0.0 .and. ( Ann_Saved_MudDischarged_Volume-((Qlost/60.0d0)*DeltaT_Mudline) ) == 0.0 ) then 
        if ( data%State%MudSystem%Ann_Kick_Saved_Volume > 1.0e-5 .and. ( data%State%MudSystem%MudVolume_InjectedFromAnn ) <= 1.0e-5 ) then 
            
            !WRITE (*,*) 'only kick enters to chokeline, Casing pressure = ', PressureGauges(2)
            
                if (data%State%MudSystem%ChokeLine_MudOrKick%First() == 0) then
                    call data%State%MudSystem%ChokeLine_Density%AddToFirst (data%State%MudSystem%Ann_KickSaved_Density)
                    call data%State%MudSystem%ChokeLine_MudDischarged_Volume%AddToFirst (0.d0)
                    call data%State%MudSystem%ChokeLine_Mud_Forehead_X%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_Mud_Forehead_section%AddToFirst (1)
                    call data%State%MudSystem%ChokeLine_Mud_Backhead_X%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_Mud_Backhead_section%AddToFirst (1)
                    call data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_MudOrKick%AddToFirst (data%State%MudSystem%Saved_Ann_MudOrKick)
                    
                    data%State%MudSystem%ChokeLineDensity_Old= data%State%MudSystem%Ann_KickSaved_Density
                    
                endif
                
                    data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)+ data%State%MudSystem%Ann_Kick_Saved_Volume   !(gal)                    
         
        endif
        
        
        do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()-2
            if ( data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) ==1 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+1) ==0 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+2) ==1 ) then
                write(*,*) 'error_location is 2'
                
                error_occured = 1
            
            endif          
        enddo          
        
        
        
        !if ( Ann_Kick_Saved_Volume == 0.0 .and. ( Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) ) > 0.0 ) then
        if ( data%State%MudSystem%Ann_Kick_Saved_Volume <= 1.0e-5 .and.  data%State%MudSystem%MudVolume_InjectedFromAnn > 1.0e-5 ) then
            
            !WRITE (*,*) 'only mud enters to chokeline'

                
             if ((data%State%MudSystem%Ann_to_Choke_2mud == .false. .and. ABS(data%State%MudSystem%ChokeLineDensity_Old - data%State%MudSystem%Ann_MudSaved_Density) >= data%State%MudSystem%DensityMixTol) .or. data%State%MudSystem%ChokeLine_MudOrKick%First() /= 0) then     ! new mud is pumped
                call data%State%MudSystem%ChokeLine_Density%AddToFirst (data%State%MudSystem%Ann_MudSaved_Density)
                call data%State%MudSystem%ChokeLine_MudDischarged_Volume%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_Mud_Forehead_X%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_Mud_Forehead_section%AddToFirst (1)
                call data%State%MudSystem%ChokeLine_Mud_Backhead_X%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_Mud_Backhead_section%AddToFirst (1)
                call data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_MudOrKick%AddToFirst (0)
             
                 data%State%MudSystem%ChokeLineDensity_Old= data%State%MudSystem%Ann_MudSaved_Density
             endif

                    !ChokeLine_MudDischarged_Volume%Array(1)= ChokeLine_MudDischarged_Volume%Array(1)+ (Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) )   !(gal) 
                    data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)+ (data%State%MudSystem%MudVolume_InjectedFromAnn)   !(gal)  
                    
                
                
        endif
        

        
        do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()-2
            if ( data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) ==1 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+1) ==0 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+2) ==1 ) then
                write(*,*) 'error_location is 3'
                error_occured = 1
                
            endif          
        enddo  
        
        
        !if ( Ann_Kick_Saved_Volume > 0.0 .and. (Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) ) > 0.0 .and. ChokeLine_MudOrKick%First() /= 0 ) then 
        if ( data%State%MudSystem%Ann_Kick_Saved_Volume > 1.0e-5 .and. (data%State%MudSystem%MudVolume_InjectedFromAnn) > 1.0e-5 .and. data%State%MudSystem%ChokeLine_MudOrKick%First() /= 0 ) then 
  
            WRITE (*,*) 'Kick Enters Choke line Last Time'

                    data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)+ data%State%MudSystem%Ann_Kick_Saved_Volume   !(gal)  
                    
                    
                    
                call data%State%MudSystem%ChokeLine_Density%AddToFirst (data%State%MudSystem%Ann_MudSaved_Density)
                !call ChokeLine_MudDischarged_Volume%AddToFirst (Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) )
                call data%State%MudSystem%ChokeLine_MudDischarged_Volume%AddToFirst (data%State%MudSystem%MudVolume_InjectedFromAnn)
                call data%State%MudSystem%ChokeLine_Mud_Forehead_X%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_Mud_Forehead_section%AddToFirst (1)
                call data%State%MudSystem%ChokeLine_Mud_Backhead_X%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_Mud_Backhead_section%AddToFirst (1)
                call data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
                call data%State%MudSystem%ChokeLine_MudOrKick%AddToFirst (0)
             
                 data%State%MudSystem%ChokeLineDensity_Old= data%State%MudSystem%Ann_MudSaved_Density

                                    
                    
                        
                
        !ELSE if ( Ann_Kick_Saved_Volume > 0.0 .and. ( Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) ) > 0.0 .and. ChokeLine_MudOrKick%First() == 0 ) then 
        ELSE if ( data%State%MudSystem%Ann_Kick_Saved_Volume > 1.0e-5 .and. ( data%State%MudSystem%MudVolume_InjectedFromAnn ) > 1.0e-5 .and. data%State%MudSystem%ChokeLine_MudOrKick%First() == 0 ) then 
            WRITE (*,*) 'Kick Enters Choke line First Time'
            


                    !ChokeLine_MudDischarged_Volume%Array(1)= ChokeLine_MudDischarged_Volume%Array(1)+ ( Ann_Saved_MudDischarged_Volume - ((Qlost/60.0d0)*DeltaT_Mudline) )   !(gal)              
                    data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(1)+ ( data%State%MudSystem%MudVolume_InjectedFromAnn )   !(gal)              


            
                    
                    call data%State%MudSystem%ChokeLine_Density%AddToFirst (data%State%MudSystem%Ann_KickSaved_Density)
                    call data%State%MudSystem%ChokeLine_MudDischarged_Volume%AddToFirst (data%State%MudSystem%Ann_Kick_Saved_Volume)
                    call data%State%MudSystem%ChokeLine_Mud_Forehead_X%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_Mud_Forehead_section%AddToFirst (1)
                    call data%State%MudSystem%ChokeLine_Mud_Backhead_X%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_Mud_Backhead_section%AddToFirst (1)
                    call data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%AddToFirst (0.0d0)
                    call data%State%MudSystem%ChokeLine_MudOrKick%AddToFirst (data%State%MudSystem%Saved_Ann_MudOrKick)
                    
                    data%State%MudSystem%ChokeLineDensity_Old= data%State%MudSystem%Ann_KickSaved_Density

                
        endif                  
                
        do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()-2
            if ( data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) ==1 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+1) ==0 .and. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud+2) ==1 ) then
                write(*,*) 'error_location is 4'
                error_occured = 1
          
            endif          
        enddo  
        
        if (error_occured == 1) then
        
                do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()
                    write(*,*) 'ChokeLine:', imud,  data%State%MudSystem%ChokeLine_Density%Array(imud) ,data%State%MudSystem%ChokeLine_MudOrKick%Array(imud)
                enddo    
                
        endif
        
        
!==========================================================      
        
       !
       !write(*,*) 'after add chokeline=='
       ! 
       ! do imud=1, ChokeLine_MudDischarged_Volume%Length()
       !     write(*,*) 'ChokeLine:', imud, ChokeLine_MudDischarged_Volume%Array(imud), ChokeLine_Density%Array(imud) ,ChokeLine_MudOrKick%Array(imud)
       ! enddo             
       !     
       !write(*,*) 'after add chokeline=='        
       ! 
       ! 
        
        
!=============== save Choke Mud data==========================
    data%State%MudSystem%ChokeMudVolumeSum= 0.d0
    !Ann_MudSaved_Density= 0.d0
    !Ann_KickSaved_Density= 0.d0
    data%State%MudSystem%Choke_Saved_MudDischarged_Volume= 0.d0
    data%State%MudSystem%Choke_Kick_Saved_Volume= 0.d0
    data%State%MudSystem%Saved_Choke_MudOrKick= 0
    
    
    
    
    do imud=1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()
        
            data%State%MudSystem%ChokeMudVolumeSum= data%State%MudSystem%ChokeMudVolumeSum + data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)
        
        if ( data%State%MudSystem%ChokeMudVolumeSum > data%State%MudSystem%ChokeLine_VolumeCapacity ) then
            
            IF (data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) == 0) THEN
                data%State%MudSystem%Choke_MudSaved_Density = data%State%MudSystem%ChokeLine_Density%Array(imud)
                data%State%MudSystem%Choke_Saved_MudDischarged_Volume = data%State%MudSystem%ChokeMudVolumeSum - data%State%MudSystem%ChokeLine_VolumeCapacity
            ELSEIF (data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) > 0 .AND. data%State%MudSystem%ChokeLine_MudOrKick%Array(imud) <100) THEN        ! 104= AIR
                data%State%MudSystem%Choke_Kick_Saved_Volume = data%State%MudSystem%ChokeMudVolumeSum - data%State%MudSystem%ChokeLine_VolumeCapacity
                data%State%MudSystem%Saved_Choke_MudOrKick= data%State%MudSystem%ChokeLine_MudOrKick%Array (imud)
                data%State%MudSystem%Choke_KickSaved_Density= data%State%MudSystem%ChokeLine_Density%Array(imud)
            END IF
            
            do ii= imud + 1, data%State%MudSystem%ChokeLine_MudDischarged_Volume%Length()
                
                IF (data%State%MudSystem%ChokeLine_MudOrKick%Array(ii) == 0) THEN
                    data%State%MudSystem%Choke_MudSaved_Density = ((data%State%MudSystem%Choke_MudSaved_Density * data%State%MudSystem%Choke_Saved_MudDischarged_Volume) + (data%State%MudSystem%ChokeLine_Density%Array(ii) * data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(ii))) / (data%State%MudSystem%Choke_Saved_MudDischarged_Volume + data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(ii))
                    data%State%MudSystem%Choke_Saved_MudDischarged_Volume = data%State%MudSystem%Choke_Saved_MudDischarged_Volume + data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(ii)
                ELSEIF (data%State%MudSystem%ChokeLine_MudOrKick%Array(ii) > 0 .AND. data%State%MudSystem%ChokeLine_MudOrKick%Array(ii) <100) THEN        ! 104= AIR
                    data%State%MudSystem%Choke_Kick_Saved_Volume = data%State%MudSystem%Choke_Kick_Saved_Volume + data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(ii)
                    data%State%MudSystem%Saved_Choke_MudOrKick= data%State%MudSystem%ChokeLine_MudOrKick%Array (ii)
                    data%State%MudSystem%Choke_KickSaved_Density= data%State%MudSystem%ChokeLine_Density%Array(ii)
                END IF
            enddo
            
            
            !WRITE (*,*) 'Choke_Saved_Mud_Volume, Choke_Kick_Saved_Volume', Choke_Saved_MudDischarged_Volume, Choke_Kick_Saved_Volume
            exit ! exits do
            
        endif
        
    enddo
data%State%MudSystem%Choke_Saved_MudDischarged_Volume_Final= data%State%MudSystem%Choke_Saved_MudDischarged_Volume !+ Choke_Kick_Saved_Volume
data%State%MudSystem%Choke_Kick_Saved_Volume_Final= data%State%MudSystem%Choke_Kick_Saved_Volume
!======================================================================       
        

        !
        !do imud=1, ChokeLine_MudDischarged_Volume%Length()
        !    write(*,*) 'a)ChokeLine:', imud, ChokeLine_MudDischarged_Volume%Array(imud) ,ChokeLine_MudOrKick%Array(imud)
        !enddo 


        !write(*,*)  'choke_Mud sum=' , sum(ChokeLine_MudDischarged_Volume%Array(:)) 
        !write(*,*)  'choke_cap=' , ChokeLine_VolumeCapacity
        !write(*,*)  'Choke_Saved_Mud=' , Choke_Saved_MudDischarged_Volume_Final
        !write(*,*)  'Choke_Saved_Kick=' , Choke_Kick_Saved_Volume_Final
        

      
!========================Choke Line================= 
         
imud=0  
    do while (imud < data%State%MudSystem%ChokeLine_Mud_Forehead_X%Length())
        imud = imud + 1        
        
            if (imud> 1) then
                data%State%MudSystem%ChokeLine_Mud_Backhead_X%Array(imud)= data%State%MudSystem%ChokeLine_Mud_Forehead_X%Array(imud-1)
                data%State%MudSystem%ChokeLine_Mud_Backhead_section%Array(imud)= data%State%MudSystem%ChokeLine_Mud_Forehead_section%Array(imud-1)
            endif
            
                
            !DirectionCoef= (Xend_PipeSection(St_Mud_Backhead_section%Array(imud))-Xstart_PipeSection(St_Mud_Backhead_section%Array(imud))) &
            !    / ABS(Xend_PipeSection(St_Mud_Backhead_section%Array(imud))-Xstart_PipeSection(St_Mud_Backhead_section%Array(imud)))
            ! +1 for string  ,   -1 for annulus
                
                                                                                                                    
            data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Array(imud)= (data%Configuration%BopStack%ChokeLineLength- data%State%MudSystem%ChokeLine_Mud_Backhead_X%Array(imud))* data%State%MudSystem%Area_ChokeLineFt !(ft^3) 
            
            data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Array(imud)= data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Array(imud)* 7.48051948d0       ! ft^3  to gal
            
            if ( data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud) <= data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Array(imud)) then
                data%State%MudSystem%ChokeLine_Mud_Forehead_section%Array(imud)= data%State%MudSystem%ChokeLine_Mud_Backhead_section%Array(imud)
                data%State%MudSystem%ChokeLine_Mud_Forehead_X%Array(imud)= data%State%MudSystem%ChokeLine_Mud_Backhead_X%Array(imud)+ (data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)/7.48051948d0)/data%State%MudSystem%Area_ChokeLineFt
                                                                            !   7.48 is for gal to ft^3
                
            else
                    
                data%State%MudSystem%isection= data%State%MudSystem%ChokeLine_Mud_Backhead_section%Array(imud)+1
                data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)- data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Array(imud)
                    
                do 
                        if (data%State%MudSystem%isection > 1) then        ! last pipe section(Chokeline exit) 
                            data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)= data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)- data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Array(imud)
                            data%State%MudSystem%ChokeLine_Mud_Forehead_X%Array(imud)= data%Configuration%BopStack%ChokeLineLength
                            data%State%MudSystem%ChokeLine_Mud_Forehead_section%Array(imud)= 1
                            if (data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(imud)<= 0.0d0)  then       ! imud is completely exited form the string
                                call data%State%MudSystem%ChokeLine_MudDischarged_Volume%Remove (imud)
                                call data%State%MudSystem%ChokeLine_Mud_Backhead_X%Remove (imud)
                                call data%State%MudSystem%ChokeLine_Mud_Backhead_section%Remove (imud)
                                call data%State%MudSystem%ChokeLine_Mud_Forehead_X%Remove (imud)
                                call data%State%MudSystem%ChokeLine_Mud_Forehead_section%Remove (imud)
                                call data%State%MudSystem%ChokeLine_Density%Remove (imud)
                                call data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Remove (imud)
                                call data%State%MudSystem%ChokeLine_EmptyVolume_inBackheadLocation%Remove (imud)
                                call data%State%MudSystem%ChokeLine_MudOrKick%Remove (imud)
                                
                            endif
                            exit
                        endif
                                 
                    data%State%MudSystem%xx= data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Array(imud)/ data%State%MudSystem%ChokeLine_VolumeCapacity   !(gal)
                        
                    if (data%State%MudSystem%xx<= 1.0) then
                        data%State%MudSystem%ChokeLine_Mud_Forehead_section%Array(imud)= data%State%MudSystem%isection
                        data%State%MudSystem%ChokeLine_Mud_Forehead_X%Array(imud)= data%State%MudSystem%xx * data%Configuration%BopStack%ChokeLineLength
                        exit
                    else
                        data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Array(imud)= data%State%MudSystem%ChokeLine_RemainedVolume_in_LastSection%Array(imud)- data%State%MudSystem%ChokeLine_VolumeCapacity
                        data%State%MudSystem%isection= data%State%MudSystem%isection+ 1
                        
                                
                    endif

                enddo
            
            endif   

    enddo
!========================Choke Line END=================
    
        !do imud=1, ChokeLine_MudDischarged_Volume%Length()
        !    write(*,*) 'b)ChokeLine:', imud, ChokeLine_MudDischarged_Volume%Array(imud) ,ChokeLine_MudOrKick%Array(imud)
        !enddo 
    
    data%State%MudSystem%ChokeOutletDensity= data%State%MudSystem%ChokeLine_Density%Last()    ! used in MudSystem
    
    

    
 
        do i=1, data%State%MudSystem%ChokeLine_MudOrKick%Length()
            !write(*,555) i,'Choke_Volume(i), type=' ,ChokeLine_MudDischarged_Volume%Array(i),ChokeLine_MudOrKick%Array(i)
        
            IF (IEEE_Is_NaN(data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(i)))      call ErrorStop('NaN in Choke Volume-Plot')
            IF (data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(i)<=0.)      call ErrorStop('Choke Volume= <=0' , data%State%MudSystem%ChokeLine_MudDischarged_Volume%Array(i))
        enddo     
    
555     FORMAT(I3,5X,A42,(f12.5),5X,I3)         
    
    
      !write(*,*) 'after sorting chokeline=='
        !IF (ANY(ChokeLine_MudOrKick%Array(:) > 0)) THEN
        !    do imud=1, ChokeLine_MudDischarged_Volume%Length()
        !        write(*,*) 'ChokeLine:', imud, ChokeLine_MudDischarged_Volume%Array(imud), ChokeLine_Density%Array(imud) ,ChokeLine_MudOrKick%Array(imud)
        !    enddo
        !END IF
        
        
        !do imud=1, Ann_MudDischarged_Volume%Length()
        !    write(*,*) 'Ann:', imud, Ann_MudDischarged_Volume%Array(imud), Ann_Density%Array(imud) ,Ann_MudOrKick%Array(imud)
        !enddo
        !
        !write(*,*) 'Ann cap=' , sum(PipeSection_VolumeCapacity(F_StringIntervalCounts+1:NoPipeSections))
        ! write(*,*) 'Ann mud sum vol=' , sum(Ann_MudDischarged_Volume%Array(:))    
        
    
    !write(*,*) '==after sorting chokeline'
    
      
    end subroutine ChokeLineMud
    
 
    
    
    
subroutine Choke_GasSound    !  is called in subroutine CirculationCodeSelect  


use CSounds
        !Use GeoElements_FluidModule
        !USE CMudPropertiesVariables
        USE MudSystemVARIABLES
use SimulationVariables !@@@
        !use ConfigurationVariables
        !USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !!use CDataDisplayConsole
   !@ use ConfigurationVariables ,  StandPipePressureDataDisplay=>StandPipePressure
        !!use CManifolds
        !use ConfigurationVariables !@
        !USE CHOKEVARIABLES
!use ConfigurationVariables !@
        !!use CChokeManifoldVariables
    use SimulationVariables
        !use CTanks
    !@use ConfigurationVariables, TripTankVolume2 => TripTankVolume, TripTankDensity2 => TripTankDensity
        !USE sROP_Other_Variables
        !USE sROP_Variables
        !use KickVARIABLESModule
        !use PressureDisplayVARIABLESModule
        !Use CError
        !Use , intrinsic :: IEEE_Arithmetic



    
    
    if ( data%State%MudSystem%ChokeLine_MudOrKick%Last() > 0 .AND. data%State%MudSystem%WellToChokeManifoldOpen == .true.) then
        !WellToChokeManifoldWasOpen
        
        data%State%MudSystem%SoundGasThroughChoke = 100  !100:chon dar adadhaye kamtar az 100 seda ghaat mishavad. eslah shavad.5.8.98  !int (min(ChokeLineFlowRate/2. , 100.))
        print* , 'SoundGasThroughChoke1=', data%State%MudSystem%SoundGasThroughChoke
        !WRITE (*,*) 'WellToChokeManifoldWasOpen-Sound', WellToChokeManifoldWasOpen
        WRITE (*,*) 'WellToChokeManifoldOpen', data%State%MudSystem%WellToChokeManifoldOpen
    else
        data%State%MudSystem%SoundGasThroughChoke = 0
        print* , 'SoundGasThroughChoke2=', data%State%MudSystem%SoundGasThroughChoke
    endif
    !print* , 'SoundGasThroughChoke3=', SoundGasThroughChoke
    

    
    call SetSoundGasThroughChoke(data%State%MudSystem%SoundGasThroughChoke)
    
    
    end subroutine Choke_GasSound    