module MudSystemModule
    
    USE MudSystemVARIABLES
use SimulationVariables !@@@
    use PressureDisplayVARIABLESModule
    USE FricPressDropVarsModule
    USE Fluid_Flow_Startup_Vars
    ! USE CMudPropertiesVariables
    USE CManifolds
    use CPumpsVariables
    use CPumps
    USE CUnityOutputs
    use CWarnings
    use DynamicIntegerArray,only: DynamicIntegerArrayType 
    use CError
    use CLog1
    use CDataDisplayConsole
    use SimulationVariables
    use CStudentStationVariables   !, PitGainLossReset=>PitGainLossZero
    use MudPropertiesModule
    
    
    implicit none
        
    real j2,j12,j13,jj2,jj12,jj13
    real  A71,A72,A73
    integer j3,B71,B77,B78
    integer j4
    real C71,C77,C78
    integer j5
    integer j6,D71,D80
    integer j7,j8,j9,j10,j11
    real E71,E72,E73
    real F71,F72,F73
    integer j14
    real G82,G83,G84
    integer j15
    real H82,H83,H84
    integer j16,K82,K83,K84,K79,K78
    integer j17,L82,L83,L84,L79,L78
    integer j18
    real M71,M77,M78, Pump1toCh,Pump2toCh,Pump3toCh,Denominator_a
    integer j19
    real N82,N83,N84
    integer j20
    integer j21
    real unityreturn


    
    real(8) DumpPump1,DumpPump2,DumpCementPump,Denominator
    real(8) Mp1Coef,Mp2Coef,CpCoef
    real(8) PumpPressure1,PumpPressure2,PumpPressure3
    integer Mp1_NoPath,Mp2_NoPath,Cp_NoPath
    real P1toSt,P2toSt,CptoSt
    real(8) MaxWorkingPressure1,MaxWorkingPressure2,MaxWorkingPressure3,MaxWorkingPressure

    REAL(8) DumpFromKelly, DumpFromFillupHead
    real(8) AddedVolumeToTank,PUMP1_Flow_Rate_Old,PUMP2_Flow_Rate_Old,PUMP3_Flow_Rate_Old
    real(8) VolumeToActive,VolumeToBellNipple,BellNipple_FlowCoef,ChokeLine_FlowCoef
    
    
    REAL RealJ2,RealJ12,RealJ13,RealJ4,RealJ18
    INTEGER active32,active33,active34,active35,active29
    
    logical condition1, condition2, condition3, condition4, condition5, condition6, condition7, condition8, condition9, condition10, condition11, condition12, condition13, condition14, condition15
    logical condition16,condition17,condition18,condition19,condition20,condition21,condition22,condition23,condition24,condition25,condition26,condition27,condition28,condition29,condition30,condition31
    logical condition32,condition33,condition34,condition35,condition36,condition37,condition38,condition39,condition40,condition41,condition42,condition43,condition44,condition45
    logical condition46,condition47,condition48,condition49,condition50,condition51,condition52,condition53,condition54,condition55,condition56,condition57,condition58
    logical condition59,condition60,condition61
    logical ac32, ac33, ac34, ac35, ac29
    logical ThereIsPathFrom_71_72_73_To_82, ThereIsPathFrom_71_72_73_To_83, ThereIsPathFrom_71_72_73_To_84
    logical DumpFromKelly_Pump1, DumpFromKelly_Pump2, DumpFromKelly_Pump3
    logical DumpFromTopDrive_Pump1,DumpFromTopDrive_Pump2,DumpFromTopDrive_Pump3
    logical DumpFromFillupHead_Pump1, DumpFromFillupHead_Pump2, DumpFromFillupHead_Pump3
    logical State1,State2, State3, State4
    type(DynamicIntegerArrayType) Pump1_Lasts,Pump2_Lasts, Pump3_Lasts
    REAL MP1_Q, MP2_Q, MP3_Q
    real TimePassed

        real(8) active_after, active_before, active_increase, total_active_increase,total_decrease,sys_total_injected
    real(8) total_annFlow,total_DeltaVPipe
    contains
    
    subroutine LineupAndPath()
    implicit none
	
!===========================================================================
!                   	          MUDLINE CODE
!===========================================================================  
   ! Initialize
    j2=0
    jj2=0
    A71=0
    A72=0
    A73=0
    RealJ2=0.0
    
    j3=0
    B71=0
    B77=0
    B78=0
    
    j4=0
    C71=0.
    C77=0.
    C78=0.
    active32=0
    active33=0
    active34=0
    active35=0
    active29=0

    
    j5=0
    
    j6=0
    D71=0
    D80=0
    
    j7=0
    
    j8=0
    
    j9=0
    j10=0
    j11=0
    
    j12=0
    jj12=0
    E71=0
    E72=0
    E73=0
    RealJ12=0.0

    j13=0
    jj13=0
    F71=0
    F72=0
    F73=0
    RealJ13=0.0
    
    j14=0
    G82=0
    G83=0
    G84=0  
    
    DumpPump1=0.
    DumpPump2=0.
    DumpCementPump=0.
    
    j15=0
    H82=0.0
    H83=0.0
    H84=0.0
    
    Mp1Coef= 0.0
    Mp1Coef= 0.0
    CpCoef= 0.0
    
    Mp1_NoPath= 0
    Mp2_NoPath= 0
    Cp_NoPath= 0
    
    j16=0
    K82=0
    K83=0
    K84=0
    K78=0
    K79=0
    
    
    j17=0
    L82=0
    L83=0
    L84=0
    L78=0
    L79=0

    j18=0
    M71=0.
    M77=0.
    M78=0.
    Pump1toCh=0.
    Pump2toCh=0.
    Pump3toCh=0.
    
    
    j19=0
    N82=0
    N83=0
    N84=0
    
    j20=0
    
    j21=0
    
   
    
!=========================================================================== 
    
                !===============TanksToMudPump1=================           
                if(condition1) then
                    j2=j2+1
                    A71=1
                    jj2=1
                endif
                    
                if(condition2) then
                    j2=j2+1
                    A72=1
                    jj2=1
                endif
                    
                if(condition3) then
                    j2=j2+1
                    A73=1
                    jj2=1
                endif
                
                !================================================
                 
                !============BellNippleToPits-FullWell==============
            if(data%State%MudSystem%FirstMudSet== 1 ) then !.and. WellisNOTFull== .false.) then       ! Well Must Be Full   !Ann_Mud_Forehead_X%Last()==AboveAnnularHeight .and. Ann_Density%Last()/=0.0) 
                if(condition4) then
                   j3=j3+1
                   B71=1
                endif
                    
                if(condition5) then
                   j3=j3+1
                    B77=1
                 endif 
                
                if(condition6) then
                  j3=j3+1
                  B78=1
               endif
                    
              endif    
                
                !================================================
            
                !============WellToChokeManifold(Through 26)==============           
                if(condition7) then
                    j4=j4+1
                    C71=1.
                endif
                    
                if(condition8) then
                    j4=j4+1
                    C77=1.
                endif
                
                if(condition45) then
                    j4=j4+1
                    C78=1.
                endif
                    if (ac32) active32=1
                    if (ac33) active33=1
                    if (ac34) active34=1
                    if (ac35) active35=1
                    if (ac29) active29=1    !BYPASS VALVE
                    
                        
                    
                !================================================
      
                
                !============ActiveTankToTripTank==============          
                    if(condition9) then
                            j5=j5+1
                    endif
                !================================================                      
                   
                !write(*,*) 'j5====' , j5
                !============TripTankToActiveTank And BellNipple==============          
                    if(condition10) then
                        j6=j6+1
                        D71=1
                    endif
                    
                    if(condition11) then
                        j6=j6+1
                        D80=1
                    endif
                !================================================     
             
                !============ActiveTankToDump==============          
                if(condition12) then
                    j7=j7+1              
                endif
                !================================================
                    
                !============TripTankToDump==============          
                if(condition13) then
                    j8=j8+1              
                endif
                !================================================                    
 
                !============WellToBellNipple==============          
                if(condition14) then
                    j9=j9+1              
                endif
                !================================================                  
                
                !============MudBucketToBellNipple==============          
                if(condition15) then
                    j10=j10+1               
                endif
                !================================================                 
                
                !============BellNippleToWell-NonFullWell==============

                
                if(condition16 .and. data%State%MudSystem%FirstMudSet== 1 .and. data%State%MudSystem%BellNippleVolume > 0.0001 .and. data%State%MudSystem%WellisNOTFull) then
                    
                    write(*,*) 'data%State%MUD(7)%Q=' , data%State%MUD(7)%Q
                    write(*,*) 'BellNippleVolume=' , data%State%MudSystem%BellNippleVolume
                    
                    
                    write(*,*) 'data%State%MudSystem%MudVolume_InjectedFromAnn-WellToBellNipple=' , data%State%MudSystem%MudVolume_InjectedFromAnn
                    
                    write(*,*) 'int:::=' , (data%State%MudSystem%Ann_Mud_Forehead_X%Last() - data%Configuration%BopStack%AboveAnnularHeight)
                    write(*,*) 'Ann_Mud_Forehead_X%Last()=' , data%State%MudSystem%Ann_Mud_Forehead_X%Last()
                    write(*,*) 'AboveAnnularHeight=' , data%Configuration%BopStack%AboveAnnularHeight
                    write(*,*) 'Ann_Density%Last()=' , data%State%MudSystem%Ann_Density%Last()
                    CALL ErrorStop('error stop1')
                    
                    j11=j11+1 
                endif               
                !================================================                  

                !===============TanksToMudPump2===================

                    if(condition17) then
                        j12=j12+1
                        E71=1
                        jj12=1
                    endif
                    
                    if(condition18) then
                        j12=j12+1
                        E72=1
                        jj12=1
                    endif
                    
                    if(condition19) then
                        j12=j12+1
                        E73=1
                        jj12=1
                    endif

                !================================================  
                    
                !===============TanksToCementPump===================
                    if(condition20) then
                        j13=j13+1
                        F71=1
                        jj13=1
                    endif
                    
                    if(condition21) then
                        j13=j13+1
                        F72=1
                        jj13=1
                    endif
                    
                    if(condition22) then
                        j13=j13+1
                        F73=1
                        jj13=1
                    endif

                !================================================                      
                    
                !===============PumpsToString===================
                    if(condition23) then
                        j14=j14+1
                        G82=1
                    endif
                    
                    if(condition24) then
                        j14=j14+1
                        G83=1
                    endif
                    
                    if(condition25) then
                        j14=j14+1
                        G84=1
                    endif
                !================================================                      

                    
                !===============PumpsToDump===================
                    if(condition26) then
                        DumpPump1=1.0
                    endif
                    
                    if(condition27) then
                        DumpPump2=1.0
                    endif
                    
                    if(condition28) then
                        DumpCementPump=1.0
                    endif
                !================================================                      
                    
                    
                !=======MudPumps1&2ToActiveTank_Through65&66==========
                    if(condition29) then
                        !write(*,*) 'condition 29'
                        j15=j15+1
                        H82=1.0
                    endif
                    
                    if(condition30) then
                        j15=j15+1
                        H83=1.0
                    endif

                !================================================                 
                    
                    
                !=======CementPumpToActiveTank_Through65==========
 
                if(condition31)    then
                    
                    H84=1.0
                    
                endif
                !================================================                     
                    
                    !write(*,*) 'condition32===' , condition32
                    
                !============MudPump1HasNoPath===================          
                if(data%State%MudSystem%condition32Final) then
                    !write(*,*) 'MudPump1HasNoPath'
                    Mp1_NoPath = 1               
                endif
                !================================================                

                !============MudPump2HasNoPath=================== 
                if(data%State%MudSystem%condition33Final) then
                    !write(*,*) 'MudPump2HasNoPath'
                    Mp2_NoPath = 1 
                endif
                !================================================                
                
                
                !============CementPumpHasNoPath===================          
                if(data%State%MudSystem%condition34Final) then
                    Cp_NoPath = 1                
                endif
                !================================================                       
 
                !===============PathsToGauge75===================
                    if(condition35) then      !Pump1 to Gauge75
                        j16=j16+1
                        K82=1
                    endif
                    
                    if(condition36) then      !Pump2 to Gauge75
                        j16=j16+1
                        K83=1
                    endif
                    
                    if(condition37) then      !Pump3 to Gauge75
                        j16=j16+1
                        K84=1
                    endif
                    
                    if(condition38) then      !String to Gauge75
                        j16=j16+1
                        K79=1
                    endif  
                    
                    if(condition39) then      !Dump to Gauge75
                        j16=j16+1
                        K78=1
                    endif                     

                !================================================                  
                                         !write(*,*) '****j16=' , j16       
                !===============PathsToGauge76===================
                    if(condition40) then      !Pump1 to Gauge76
                        j17=j17+1
                        L82=1
                    endif
                    
                    if(condition41) then      !Pump2 to Gauge76
                        j17=j17+1
                        L83=1
                    endif
                    
                    if(condition42) then      !Pump3 to Gauge76
                        j17=j17+1
                        L84=1
                    endif
                    
                    if(condition43) then      !String to Gauge76
                        j17=j17+1
                        L79=1
                    endif
                    
                    if(condition44) then      !Dump to Gauge76
                        j17=j17+1
                        L78=1
                    endif                     

                !================================================                 
                
                !====Pump1-StandPipeManifoldToChokeManifold-Through ChokeLine====          
                    if(condition46) then
                        j18=j18+1
                        M71=1.
                        Pump1toCh= 1.
                    endif
                    
                    if(condition47) then
                        j18=j18+1
                        M77=1.
                        Pump1toCh= 1.
                    endif
                    
                    if(condition48) then
                        j18=j18+1
                        M78=1.
                        Pump1toCh= 1.
                    endif                                                       
                !=================================================================                 
           
                
                !====Pump2-StandPipeManifoldToChokeManifold-Through ChokeLine==== 
                    if(condition49) then
                        j18=j18+1
                        M71=1.
                        Pump2toCh= 1.
                    endif
                    
                    if(condition50) then
                        j18=j18+1
                        M77=1.
                        Pump2toCh= 1.
                    endif
                    
                    if(condition51) then
                        j18=j18+1
                        M78=1.
                        Pump2toCh= 1.
                    endif                
                !=================================================================                 
                
                
                !====Pump3-StandPipeManifoldToChokeManifold-Through ChokeLine==== 
                    if(condition52) then
                        j18=j18+1
                        M71=1.
                        Pump3toCh= 1.
                    endif
                    
                    if(condition53) then
                        j18=j18+1
                        M77=1.
                        Pump3toCh= 1.
                    endif
                    
                    if(condition54) then
                        j18=j18+1
                        M78=1.
                        Pump3toCh= 1.
                    endif                      
                !=================================================================                 
                
                
                !===============PumpsToWell_KillLine============
                    if(condition55)    then
                        j19=j19+1
                        N82=1
                    endif
                    
                    if(condition56) then
                        j19=j19+1
                        N83=1
                    endif
                    
                    if(condition57) then
                        j19=j19+1
                        N84=1
                    endif
                !================================================                
            
                !===============WellToChokeLineGauge============
                if(condition58)    then
                        j20=j20+1
                endif
                
                if (j20>0) then
                    data%State%MudSystem%WellToChokeLineGauge= .true.
                else
                    data%State%MudSystem%WellToChokeLineGauge= .false.
                endif
                !================================================ 
                
                                
                !============ChokeLineGaugeToTanks===============          
                    if(condition59) then
                        j21=j21+1
                    endif
                    
                    if(condition60) then
                        j21=j21+1
                    endif
                    
                    if(condition61) then
                        j21=j21+1
                    endif 
                    
                if (j21>0) then
                    data%State%MudSystem%ChokeLineGaugeToTanks= .true.
                else
                    data%State%MudSystem%ChokeLineGaugeToTanks= .false.
                endif 
                !================================================                

	
	end subroutine 
	
    subroutine main
        Use GeoElements_FluidModule
        use SimulationVariables
        USE CHOKEVARIABLES
use SimulationVariables !@
        use CDataDisplayConsole
    use SimulationVariables
        use SimulationVariables !@
        USE CHOKEVARIABLES
use SimulationVariables !@
        use CChokeManifoldVariables
    use SimulationVariables
        use CTanks
    use SimulationVariables
        use KickVARIABLESModule
        use CHoistingVariables
    use SimulationVariables
        ! use CSimulationVariables
        
        implicit none
        Integer I

        data%State%MudSystem%MudSys_timeCounter = data%State%MudSystem%MudSys_timeCounter + 1
        if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
            data%State%MudSystem%MudSys_timeCounter= 0
        endif  
 
        !WRITE (*,*) 'MudSys_timeCounter', MudSys_timeCounter
        if (data%Configuration%Pumps%MudPump1ReliefValveIsSet==.false.) data%Configuration%Pumps%MudPump1ReliefValvePressure=6000.
        if (data%Configuration%Pumps%MudPump2ReliefValveIsSet==.false.) data%Configuration%Pumps%MudPump2ReliefValvePressure=6000. 
        if (data%Configuration%Pumps%CementPumpReliefValveIsSet==.false.) data%Configuration%Pumps%CementPumpReliefValvePressure=6000.     
        !===========================================================================================================================
        !===========================================================================================================================
        !       >>> Should Be on Top of Other Codes <<<
                    
       
        !ActiveTankVolume=  ActiveMudVolumeGal       ! update from student input
        !ActiveTankDensity=  ActiveDensity       ! update from student input
        !ReserveTankVolume= ReserveMudVolumeGal       ! update from student input
        !ReserveTankDensity= ReserveDensity       ! update from student input  
        if (j7 > 0) then    !ActiveTankToDump
            data%State%MudSystem%ActiveTankDensity= 0.
            data%State%MudSystem%ActiveTankVolume= 0.
        endif        
        
        if (j8 > 0) then    !TripTankToDump
            data%State%MudSystem%TripTankDensityCalc= 0.
            data%State%MudSystem%TripTankVolumeCalc= 0.
        endif
        !===========================================================================================================================
        !=========================================================================================================================== 
        if (j15 > 0) then    !MudPumps1&2ToActiveTank_Through65&66
            !write(*,*) 'j15 is open'
            ! << if H82 or H83 or H4 are open, no flow goes to other parts of system >>             
            if (j2>0) Mp1Coef= 1.0
            if (j12>0) Mp2Coef= 1.0
            if (j2 /= 0 .or. j12/= 0) then
                data%State%MudSystem%ActiveTankDensity = (data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume+ Mp1Coef*data%State%MudSystem%Mp1Density*(data%State%Pump(1)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.) + Mp2Coef*data%State%MudSystem%Mp2Density*(data%State%Pump(2)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.))/ & 
                        (data%State%MudSystem%ActiveTankVolume+ Mp1Coef*(data%State%Pump(1)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.) + Mp2Coef*(data%State%Pump(2)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.))
                data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ Mp1Coef*data%State%Pump(1)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60. + Mp2Coef*data%State%Pump(2)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60. 
                !write(*,*) 'active by j15'
            endif
            data%State%MudSystem%ActiveTankVolume=min(data%State%MudSystem%ActiveTankVolume , data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)
            !if ActiveTankVolume is higher, excess amount is dumped                
        endif
        if (H84 > 0.0) then         !CementPumpToCementTank_Through67            
            if (j13>0) CpCoef= 1.0
            data%State%MudSystem%CementTankDensityCalc= (data%State%MudSystem%CementTankDensityCalc*data%State%MudSystem%CementTankVolumeCalc+ CpCoef*data%State%MudSystem%Mp3Density*(data%State%Pump(3)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.) ) / & 
                    (data%State%MudSystem%CementTankVolumeCalc+CpCoef*(data%State%Pump(3)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.))
            data%State%MudSystem%CementTankVolumeCalc= data%State%MudSystem%CementTankVolumeCalc+ CpCoef*(data%State%Pump(3)%Flow_Rate*data%State%MudSystem%DeltaT_Mudline/60.)
        endif
        !===========================================================================================================================
        !===========================================================================================================================
        !              DUMP Path           
        data%State%MudSystem%PumpsDumpVolume= data%State%MudSystem%PumpsDumpVolume+    (jj2*(1-H82)*DumpPump1*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*DumpPump2*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*DumpCementPump*data%State%Pump(3)%Flow_Rate) *data%State%MudSystem%DeltaT_Mudline/60.
        data%State%MudSystem%PumpsDumpFlowRate=    jj2*(1-H82)*DumpPump1*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*DumpPump2*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*DumpCementPump*data%State%Pump(3)%Flow_Rate
        !write(*,*) 'PumpsDumpFlowRate=' , PumpsDumpFlowRate

        if (data%Configuration%Hoisting%DriveType==1 .and. data%State%MudSystem%PumpsDumpFlowRate > 0.0 .and. (DumpFromKelly_Pump1 .or. DumpFromKelly_Pump2 .or. DumpFromKelly_Pump3)) then
            !write(*,*) 'Set_FlowFromKelly(.TRUE.)'
            call Activate_PumpWithKellyDisconnected()
            !write(*,*) 'PumpsDumpFlowRate=' , PumpsDumpFlowRate
            CALL Set_FlowFromKelly(min(data%State%MudSystem%PumpsDumpFlowRate/6.,100.)) ! .TRUE. before
        elseif (data%Configuration%Hoisting%DriveType==1) then
            call Deactivate_PumpWithKellyDisconnected()
            CALL Set_FlowFromKelly(0.0) ! .FALSE. before
            !write(*,*) 'Set_FlowFromKelly(.FALSE.)'
        endif
        !write(*,*) 'DumpFromFillupHead_Pump1=' , DumpFromFillupHead_Pump1
        if (data%Configuration%Hoisting%DriveType==0 .and. data%State%MudSystem%PumpsDumpFlowRate > 0.0 .and. (DumpFromTopDrive_Pump1 .or. DumpFromTopDrive_Pump2 .or. DumpFromTopDrive_Pump3)) then
            !write(*,*) 'Set_FlowFromKelly(.TRUE.)'
            call Activate_PumpWithTopdriveDisconnected()
            CALL Set_FlowFromKelly(min(data%State%MudSystem%PumpsDumpFlowRate/6.,100.)) ! .TRUE. before
        elseif (data%Configuration%Hoisting%DriveType==0) then
            call Deactivate_PumpWithTopdriveDisconnected()
            CALL Set_FlowFromKelly(0.0) ! .FALSE. before
            !write(*,*) 'Set_FlowFromKelly(.FALSE.)'
        endif
        if (data%State%MudSystem%PumpsDumpFlowRate > 0.0 .and. (DumpFromFillupHead_Pump1 .or. DumpFromFillupHead_Pump2 .or. DumpFromFillupHead_Pump3)) then            
            !call Activate_PumpWithKellyDisconnected()
            CALL Set_FlowFromFillupHead(min(data%State%MudSystem%PumpsDumpFlowRate/6.,100.)) ! .TRUE. before
        else
            !call Deactivate_PumpWithKellyDisconnected()
            CALL Set_FlowFromFillupHead(0.0) ! .FALSE. before
        endif                  
        !####C_Program -----> DriveType = 
        !                               = 0    TopDrive_DriveType
        !                               = 1    Kelly_DriveType
        !===========================================================================================================================
        !===========================================================================================================================              
        ! ******         Calculating Maximum Working Pressure
        if (data%Configuration%Pumps%MudPump1ReliefValveIsSet) then
            MaxWorkingPressure1= data%Configuration%Pumps%MudPump1ReliefValvePressure
        else
            MaxWorkingPressure1= 6000. !psi
        endif        
        if (data%Configuration%Pumps%MudPump2ReliefValveIsSet) then
            MaxWorkingPressure2= data%Configuration%Pumps%MudPump2ReliefValvePressure
        else    
            MaxWorkingPressure2= 6000. !psi
        endif
        if (data%Configuration%Pumps%CementPumpReliefValveIsSet) then
            MaxWorkingPressure3= data%Configuration%Pumps%CementPumpReliefValveIsSet
        else
            MaxWorkingPressure3= 6000. !psi
        endif
        if (State1) then
            MaxWorkingPressure= min(MaxWorkingPressure1 , MaxWorkingPressure2 , MaxWorkingPressure3)
            MaxWorkingPressure1= MaxWorkingPressure
            MaxWorkingPressure2= MaxWorkingPressure
            MaxWorkingPressure3= MaxWorkingPressure
        endif
        if (State2) then
            MaxWorkingPressure= min(MaxWorkingPressure1 , MaxWorkingPressure2)
            MaxWorkingPressure1= MaxWorkingPressure
            MaxWorkingPressure2= MaxWorkingPressure
        endif                
        if (State3) then
            MaxWorkingPressure= min(MaxWorkingPressure1 , MaxWorkingPressure3)
            MaxWorkingPressure1= MaxWorkingPressure
            MaxWorkingPressure3= MaxWorkingPressure
        endif  
        if (State4) then
            MaxWorkingPressure= min(MaxWorkingPressure2 , MaxWorkingPressure3)
            MaxWorkingPressure2= MaxWorkingPressure
            MaxWorkingPressure3= MaxWorkingPressure
        endif
        !                      Calculating Maximum Working Pressure     ******            
        !===========================================================================================================================
        !=========================================================================================================================== 
                    
                    
        ! ******         Blown Conditions           
    
        !G:             PumpsToString Coefficient
        !jJ2,Jj12,Jj13:    TanksToMudPump Coefficient
        !H:             Pumps To Tank_Through65 or 67 Coefficient            

        !write(*,*) 'j12=' , j12
        !write(*,*) 'H83=' , H83
        !write(*,*) 'DumpPump2=' , DumpPump2
        !write(*,*) 'G83=' , G83
        PumpPressure1= jj2*(1-H82)*(1-DumpPump1)*G82* data%State%PressureDisplay%PressureGauges(1)
        PumpPressure2= jj12*(1-H83)*(1-DumpPump2)*G83* data%State%PressureDisplay%PressureGauges(1)
        PumpPressure3= jj13*(1-H84)*(1-DumpCementPump)*G84* data%State%PressureDisplay%PressureGauges(1)
        !
        !write(*,*) 'jj2 , H82 , DumpPump1 , G82,PresCsureGauges(1)=' , jj2 , H82 , DumpPump1 , G82,PressureGauges(1)
        !write(*,*) '1)PumpPressure1=' , PumpPressure1        
        !write(*,*) 'PumpPressure2=' , PumpPressure2
        data%State%FricPressDrop%PumpToManifoldMudVol = 3.0 * 42.0
        !PumpToManifoldCompressedMudVol = PumpToManifoldCompressedMudVol + MP1_Q / ConvMinToSec * dt
        !PumpToManifoldDeltaPDueToCompressibility = PumpToManifoldCompressedMudVol / (MudCompressibility * PumpToManifoldMudVol) 
        IF(Mp1_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_82 .and. MP1_Q > 0.0) then
            data%State%FricPressDrop%PumpToManifoldCompressedMudVol = data%State%FricPressDrop%PumpToManifoldCompressedMudVol + MP1_Q / ConvMinToSec * dt
            PumpPressure1=  data%State%FricPressDrop%PumpToManifoldCompressedMudVol / (MudCompressibility * data%State%FricPressDrop%PumpToManifoldMudVol)
            write(*,*) '21)PumpPressure1=' , PumpPressure1            
            WRITE (*,*) ' valve 1 ', Manifold%Valve(1)%Status
            WRITE (*,*) ' valve 4 ', Manifold%Valve(4)%Status
            WRITE (*,*) ' valve 6 ', Manifold%Valve(6)%Status
            WRITE (*,*) ' valve 7 ', Manifold%Valve(7)%Status
            WRITE (*,*) ' valve 8 ', Manifold%Valve(8)%Status
            WRITE (*,*) ' valve 9 ', Manifold%Valve(9)%Status
            WRITE (*,*) ' valve 13 ', Manifold%Valve(13)%Status
            WRITE (*,*) ' valve 68 ', Manifold%Valve(68)%Status
            WRITE (*,*) ' valve 69 ', Manifold%Valve(69)%Status
            WRITE (*,*) ' valve 48 ', Manifold%Valve(48)%Status
            !call DisplayOpenPathsWrite()
        ENDIF  
        
        IF(Mp2_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_83 .and. MP2_Q > 0.0 ) then
            data%State%FricPressDrop%PumpToManifoldCompressedMudVol = data%State%FricPressDrop%PumpToManifoldCompressedMudVol + MP2_Q / ConvMinToSec * dt
            PumpPressure2=  data%State%FricPressDrop%PumpToManifoldCompressedMudVol / (MudCompressibility * data%State%FricPressDrop%PumpToManifoldMudVol)
            write(*,*) '22)PumpPressure1=' , PumpPressure2            
            WRITE (*,*) ' -valve 1 ', Manifold%Valve(1)%Status
            WRITE (*,*) ' -valve 4 ', Manifold%Valve(4)%Status
            WRITE (*,*) ' -valve 6 ', Manifold%Valve(6)%Status
            WRITE (*,*) ' -valve 7 ', Manifold%Valve(7)%Status
            WRITE (*,*) ' -valve 8 ', Manifold%Valve(8)%Status
            WRITE (*,*) ' -valve 9 ', Manifold%Valve(9)%Status
            WRITE (*,*) ' -valve 13 ', Manifold%Valve(13)%Status
            WRITE (*,*) ' -valve 68 ', Manifold%Valve(68)%Status
            WRITE (*,*) ' -valve 69 ', Manifold%Valve(69)%Status
            WRITE (*,*) ' -valve 48 ', Manifold%Valve(48)%Status
            !call DisplayOpenPathsWrites()
        ENDIF

        IF(Cp_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_84 .AND. MP3_Q > 0.0 ) then                
            data%State%FricPressDrop%PumpToManifoldCompressedMudVol = data%State%FricPressDrop%PumpToManifoldCompressedMudVol + MP3_Q / ConvMinToSec * dt
            PumpPressure3=  data%State%FricPressDrop%PumpToManifoldCompressedMudVol / (MudCompressibility * data%State%FricPressDrop%PumpToManifoldMudVol)
        ENDIF                  
        !*****************************************************************************
        !if(((Mp1_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_82) .or. ( PumpPressure1 >= MaxWorkingPressure1 )       &
            !.or.(J14> 0 .and. j4==0 .and. j9==0 .and. NOT(ALLOCATED(GasPocketWeight%Array)))) .and. MP1_Q > 0.0 ) then
                !write(*,*) ' failurrrrre '

        if (PumpPressure1 >= MaxWorkingPressure1 .and. MP1_Q > 0.0) then
            write(*,*) 'mp1,if=' , PumpPressure1 , MaxWorkingPressure1 , MP1_Q
            data%State%MudSystem%Pump1BlownCount = data%State%MudSystem%Pump1BlownCount + 1
            !if (Pump1BlownStarted == .FALSE.) then
            !    write(*,*) 'if (Pump1BlownStarted == .FALSE. ) then' 
            !    Pump1BlownInTimeStep = SimulationTime + BlownThresholdInSecond
            !    Pump1BlownStarted = .TRUE.
            !endif
            !write(*,*) 'SimulationTime===', SimulationTime, Pump1BlownInTimeStep
            if(data%Configuration%Pumps%MudPump1ReliefValveIsSet .and. data%State%MudSystem%Pump1BlownCount >= BlownThreshold) then
                write(*,*) 'valve 65 open, BLOWN'
                call ChangeValve(65, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                data%State%MudSystem%Pump1BlownCount = 0
                !Pump1BlownStarted = .FALSE.
            !else
            !    write(*,*) 'PumpPressure1= 6000  psi'
            !    PumpPressure1= 6000. !psi
            endif
        !else
            !Pump1BlownInTimeStep = 0
            !Pump1BlownStarted = .FALSE.
            !write(*,*) 'Pump1BlownStarted = .FALSE.' 
        endif                
        
        !write(*,*) ' valve 65=' , Valve(65)%Status
        !if(((Mp2_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_83) .or. PumpPressure2 >= MaxWorkingPressure2        &
        !.or.(J14> 0 .and. j4==0 .and. j9==0 .and. NOT(ALLOCATED(GasPocketWeight%Array))) ) .and. MP2_Q > 0.0 ) then

        if(PumpPressure2 >= MaxWorkingPressure2  .and. MP2_Q > 0.0 ) then   
            write(*,*) 'mp2,if=' , PumpPressure2 , MaxWorkingPressure2 , MP2_Q
            data%State%MudSystem%Pump2BlownCount = data%State%MudSystem%Pump2BlownCount + 1
            !if (Pump2BlownStarted == .FALSE. ) then
            !    Pump2BlownInTimeStep = SimulationTime + BlownThresholdInSecond
            !    Pump2BlownStarted = .TRUE.
            !endif
            !if (MudPump2ReliefValveIsSet .and. SimulationTime >= Pump2BlownInTimeStep .and. Pump2BlownStarted) then
            if (data%Configuration%Pumps%MudPump2ReliefValveIsSet .and. data%State%MudSystem%Pump2BlownCount >= BlownThreshold) then
                write(*,*) 'valve 66 open, BLOWN'
                call ChangeValve(66, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                data%State%MudSystem%Pump2BlownCount = 0
                !Pump2BlownInTimeStep = 0
                !Pump2BlownStarted = .FALSE.
            !else
            !    PumpPressure2= 6000. !psi
            endif
        !else
            !Pump2BlownInTimeStep = 0
            !Pump2BlownStarted = .FALSE.
        endif
        !if(((Cp_NoPath == 1 .and. ThereIsPathFrom_71_72_73_To_84) .or. PumpPressure3 >= MaxWorkingPressure3         &
        !.or.(J14> 0 .and. j4==0 .and. j9==0 .and. NOT(ALLOCATED(GasPocketWeight%Array))))  .and. MP3_Q > 0.0 ) then 
                    
        if(PumpPressure3 >= MaxWorkingPressure3 .and. MP3_Q > 0.0 ) then                     
            data%State%MudSystem%Pump3BlownCount = data%State%MudSystem%Pump3BlownCount + 1
            if (data%Configuration%Pumps%CementPumpReliefValveIsSet .and. data%State%MudSystem%Pump3BlownCount >= BlownThreshold) then
                !write(*,*) 'valve 67 open, BLOWN'
                call ChangeValve(67, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                data%State%MudSystem%Pump3BlownCount = 0
            !else
            !    PumpPressure3= 6000. !psi
            endif
        !else
            !Pump3BlownInTimeStep = 0
            !Pump3BlownStarted = .FALSE.
        endif
        !write(*,*) '3)PumpPressure1=' , PumpPressure1
        if (PumpPressure1>= 6000.) then
            data%State%MudSystem%Pump1BlownCount = data%State%MudSystem%Pump1BlownCount + 1
            if(data%State%MudSystem%Pump1BlownCount >= BlownThreshold) then
                call ChangeValve(65, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                call Activate_Pump1Failure()
                data%State%MudSystem%Pump1OffFailure= .true.
                data%State%MudSystem%Pump1BlownCount = 0
            endif
        !else
            !Pump1BlownInTimeStep = 0
            !Pump1BlownStarted = .FALSE.
        endif
        
        if (PumpPressure2>= 6000.) then
            data%State%MudSystem%Pump2BlownCount = data%State%MudSystem%Pump2BlownCount + 1
            if(data%State%MudSystem%Pump2BlownCount >= BlownThreshold) then
                call ChangeValve(66, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                call Activate_Pump2Failure()
                data%State%MudSystem%Pump2OffFailure= .true.
                data%State%MudSystem%Pump2BlownCount = 0
            endif
        !else
            !Pump2BlownInTimeStep = 0
            !Pump2BlownStarted = .FALSE.
        endif
        
        if (PumpPressure3>= 6000.) then
            data%State%MudSystem%Pump3BlownCount = data%State%MudSystem%Pump3BlownCount + 1
            if(data%State%MudSystem%Pump3BlownCount >= BlownThreshold) then
                call ChangeValve(67, .TRUE.)
                data%State%FricPressDrop%PumpToManifoldCompressedMudVol= 0.0
                call Activate_Pump3Failure()
                data%State%MudSystem%Pump3OffFailure= .true.
                data%State%MudSystem%Pump3BlownCount = 0
            endif
        !else
            !Pump3BlownInTimeStep = 0
            !Pump3BlownStarted = .FALSE.
        endif
        !                                   Blown Conditions      ********                      
        !===========================================================================================================================
        !===========================================================================================================================            
        if (j9 > 0 ) then   !.and. WellisNOTFull== .false.) then    !WellToBellNipple
            !write(*,*) 'j9 is open'
            !data%State%MUD(7)%Q= ( Ann_Saved_MudDischarged_Volume_Final+Ann_Kick_Saved_Volume_Final - ((Qlost/60.0d0)*DeltaT_Mudline) )*60.d0/DeltaT_Mudline
            data%State%MUD(7)%Q= ( data%State%MudSystem%MudVolume_InjectedFromAnn + data%State%MudSystem%Ann_Kick_Saved_Volume )*60.d0/data%State%MudSystem%DeltaT_Mudline    !Injected is referred only to Mud
            if (j4 > 0) then
                BellNipple_FlowCoef= 13.625/(13.625+data%Configuration%BopStack%ChokeLineId)          ! 13.625= BellNipple ID (inch)
                data%State%MUD(7)%Q= BellNipple_FlowCoef * data%State%MUD(7)%Q
            endif                    
                    
            !total_annFlow= total_annFlow+(AnnulusFlowRateFinal/600.d0)
            !total_DeltaVPipe= total_DeltaVPipe + DeltaVolumePipe
            !write(*,*) 'total_annFlow,total_DeltaVPipe' , total_annFlow,total_DeltaVPipe
            if (data%State%MUD(7)%Q < 0.0 )   data%State%MUD(7)%Q= 0.0     !.or. WellisNOTFull== .true.)      data%State%MUD(7)%Q= 0.0
            !!AnnulusFlowRateFinal: flow from string mud  ,   DeltaVolumeOp: due to trip in 
            
            !write(*,*) 'data%State%MUD(7)%Q=' , data%State%MUD(7)%Q
            !write(*,*) 'data%State%MudSystem%MudVolume_InjectedFromAnn-WellToBellNipple=' , data%State%MudSystem%MudVolume_InjectedFromAnn
            !write(*,*) 'Ann_Kick_Saved_Volume=' , Ann_Kick_Saved_Volume
            sys_total_injected= sys_total_injected+ data%State%MudSystem%MudVolume_InjectedFromAnn
            if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
                sys_total_injected= 0.
            endif
            !write(*,*) 'sys_total_injected=' , sys_total_injected
            !WellOutletDensity= Ann_Density%Last()   !    (ppg)      <<< in CirculationCodeSelect Code
            if ((data%State%MudSystem%BellNippleVolume+((data%State%MUD(7)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)) /= 0.0) then
                data%State%MudSystem%BellNippleDensity= ((data%State%MudSystem%BellNippleDensity*data%State%MudSystem%BellNippleVolume)+(data%State%MudSystem%WellOutletDensity*(data%State%MUD(7)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%BellNippleVolume+((data%State%MUD(7)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
            else
                data%State%MudSystem%BellNippleDensity= 0.0
            endif
            !IF (WellisNOTFull== .false.) THEN ! well must be full to do this order
            data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume+ ((data%State%MUD(7)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
            !ENDIF
            VolumeToBellNipple= VolumeToBellNipple + data%State%MudSystem%BellNippleVolume
            !write(*,*) 'VolumeToBellNipple*****=' , VolumeToBellNipple
            !write(*,*) 'BellNippleVolume in j9=' , BellNippleVolume , data%State%MUD(7)%Q
        endif
            
        if (j9 == 0 ) then  !.or. WellisNOTFull== .true.) then
            !write(*,*) 'WellisNOTFull=' , WellisNOTFull
            data%State%MUD(7)%Q=0.0       ! for normal circulation input
        endif
        
        if (j9 > 0) then
            data%State%MudSystem%WellToPitsOpen= .true.
        else
            data%State%MudSystem%WellToPitsOpen= .false.
        endif            
        !===========================================================================================================================
        !===========================================================================================================================
        if (j10 > 0) then    !MudBucketToBellNipple
            !write(*,*) 'j10 is open'
            !MudBucketVolume= 0.
            !MudBucketDensity= 0.
            ! MudBucketVolume gets value in DisconnectingPipe subroutine
            data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume+ data%State%MudSystem%MudBucketVolume
            data%State%MudSystem%BellNippleDensity= data%State%MudSystem%ActiveTankDensity
            data%State%MudSystem%MudBucketVolume= 0.
        endif            
        !===========================================================================================================================
        !===========================================================================================================================            
        if (j6 > 0) then    !TripTankToActiveTank And BellNipple
            !write(*,*) 'j6 is open'
            !write(*,*) 'active by j6'
            data%State%MUD(6)%Q= 300.       ! constant flow rate(gpm)
            data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc - ((data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)                        
            !write(*,*) 'ActiveTankVolume before=', ActiveTankVolume
            if (j6 == 1 .and. D71==1) then
                !write(*,*) 'add to active'
                data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%TripTankDensityCalc*(data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+((data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
                !write(*,*) 'ActiveTankVolume after=', ActiveTankVolume
                
            endif                    
                
            if (j6 == 1 .and. D80==1) then
                data%State%MudSystem%BellNippleDensity= ((data%State%MudSystem%BellNippleDensity*data%State%MudSystem%BellNippleVolume)+(data%State%MudSystem%TripTankDensityCalc*(data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%BellNippleVolume+((data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume+ ((data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
            endif 
                    
            if (j6 == 2) then
                data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%TripTankDensityCalc*(0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+((0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                data%State%MudSystem%BellNippleDensity= ((data%State%MudSystem%BellNippleDensity*data%State%MudSystem%BellNippleVolume)+(data%State%MudSystem%TripTankDensityCalc*(0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%BellNippleVolume+((0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                
                data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume+ ((0.5*data%State%MUD(6)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
            endif    
            data%State%MudSystem%ActiveTankVolume=min(data%State%MudSystem%ActiveTankVolume , data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)
            !if ActiveTankVolume is higher, excess amount is dumped                 
        endif
        
        if (j6 == 0) then
            data%State%MUD(6)%Q=0.0
        endif 
        !===========================================================================================================================
        !=========================================================================================================================== 
        CALL Set_FlowFromReturnLine(.false.)
        if (j3 > 0) then    !BellNippleToPits-FullWell      - must be after **WellToBellNipple(j9)**
            !write(*,*) 'j3 is open'
            !write(*,*) 'active by j3'
            !BellNipple flow rate= sum flow rate (well+ mudbucket+ triptank)
            !Well to BellNipple: BellNippleVolume
            !MudBucket to BellNipple: BellNippleVolume
            !TripTnak to BellNipple: BellNippleVolume
            data%State%MUD(3)%Q = (data%State%MudSystem%BellNippleVolume/data%State%MudSystem%DeltaT_Mudline)*60.d0        ! (gpm)
            !write(*,*) 'BellNippleVolume in j3 =' ,  BellNippleVolume
            !write(*,*) 'data%State%MUD(3)%Q =' ,  data%State%MUD(3)%Q
            call Set_FlowRate(real(100.*min(data%State%MUD(3)%Q,data%State%MudSystem%PedalMeter)/data%State%MudSystem%PedalMeter, 8))        ! for unity display
            unityreturn = real(100.*min(data%State%MUD(3)%Q,data%State%MudSystem%PedalMeter)/data%State%MudSystem%PedalMeter, 8)
            !write(*,*) 'unity return=' , real(100.*min(data%State%MUD(3)%Q,PedalMeter)/PedalMeter, 8)
            if (data%State%MUD(3)%Q > data%State%MudSystem%PedalMeter .and. B78==0) then
                data%State%MudSystem%BellNippleDumpVolume= data%State%MudSystem%BellNippleDumpVolume + ((data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline - (data%State%MudSystem%PedalMeter/60.)*data%State%MudSystem%DeltaT_Mudline)
                !BellNippleDumpRate= data%State%MUD(3)%Q - PedalMeter
                CALL Set_FlowFromReturnLine(.TRUE.)        ! for unity display
            endif
            !VolumeToActive = VolumeToActive + BellNippleVolume
            !write(*,*) 'VolumeToActive*******=' , VolumeToActive
            active_before= data%State%MudSystem%ActiveTankVolume
            data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume- ((data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) ! to be 0.
            if  ( data%State%MudSystem%BellNippleDensity > 1.0) then
                if (j3 == 1 .and. B71==1) then  !(volumes in galon)
                    data%State%MUD(3)%Q = min(data%State%MUD(3)%Q , data%State%MudSystem%PedalMeter)
                    !write(*,*) 'data%State%MUD(3)%Q=' , data%State%MUD(3)%Q
                    IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%BellNippleDensity*(data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+((data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        !write(*,*) 'active increase bell 1=' , ((data%State%MUD(3)%Q/60.)*DeltaT_Mudline)
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%BellNippleDensity > data%State%MudSystem%ActiveTankDensity) THEN
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((20.8d0-data%State%MudSystem%BellNippleDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)       ! asumed cutting density = 20.8 ppg
                        !write(*,*) 'active increase bell 2=' , ((20.8d0-BellNippleDensity)/(20.8d0-ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*DeltaT_Mudline) 
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%BellNippleDensity < 5.0) THEN                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((2.d0-data%State%MudSystem%BellNippleDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)       ! asumed GAS density = 2.0 ppg
                        !write(*,*) 'active increase bell 3=' , ((2.d0-BellNippleDensity)/(2.d0-ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*DeltaT_Mudline) 
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%BellNippleDensity .and. data%State%MudSystem%BellNippleDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                        !write(*,*) ' Auto true 3'
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        !write(*,*) 'active increase bell 4=' , ((data%State%MUD(3)%Q/60.d0)*DeltaT_Mudline)
                    ENDIF
                endif
                if (j3 == 1 .and. B77==1) then
                    data%State%MUD(3)%Q = min(data%State%MUD(3)%Q , data%State%MudSystem%PedalMeter)
                    IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%BellNippleDensity*(data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+((data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ (data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%BellNippleDensity > data%State%MudSystem%ActiveTankDensity) THEN
                        AddedVolumeToTank= ((20.8d0-data%State%MudSystem%BellNippleDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)    
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%BellNippleDensity < 5.0) THEN
                        AddedVolumeToTank= ((2.d0-data%State%MudSystem%BellNippleDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)        ! asumed GAS density = 2.0 ppg
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                    ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%BellNippleDensity .and. data%State%MudSystem%BellNippleDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                        AddedVolumeToTank= ((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline) 
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                    ENDIF
                endif                    
                if (j3 == 1 .and. B78==1) then
                    data%State%MudSystem%BellNippleDumpVolume= data%State%MudSystem%BellNippleDumpVolume+ (data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline
                    !BellNippleDumpRate= data%State%MUD(3)%Q
                endif
                    if (j3 == 2) then       !78 is not allowded in this position
                        
                        data%State%MUD(3)%Q = min(data%State%MUD(3)%Q , data%State%MudSystem%PedalMeter)
                                                
                            IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN
                                
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%BellNippleDensity*(0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+((0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%BellNippleDensity*(0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+((0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ ((0.5*data%State%MUD(3)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%BellNippleDensity > data%State%MudSystem%ActiveTankDensity) THEN
                                
                                
                        AddedVolumeToTank= ((20.8d0-data%State%MudSystem%BellNippleDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*((0.5d0*data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                               
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank 
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= ((2.d0-data%State%MudSystem%BellNippleDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*((0.5d0*data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)      ! asumed GAS density = 2.0 ppg
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%BellNippleDensity .and. data%State%MudSystem%BellNippleDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= ((data%State%MUD(3)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline) 
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank                                
                                
                                
                            ENDIF
                            
                                
                    endif  
                    
                endif   !( BellNippleDensity > 1.0) then
            
                    active_after= data%State%MudSystem%ActiveTankVolume
                    
                    active_increase = active_after - active_before
                    
                    total_active_increase= total_active_increase + active_increase
                    
                    if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
                        total_active_increase= 0.
                    endif
                    
                    !write(*,*) 'total_active_increase=' , total_active_increase
            
            
                    
                    !write(*,*) 'ReturnFlowRate=data%State%MUD(3)%Q= after' , data%State%MUD(3)%Q
                    
                    data%State%MudSystem%ReturnFlowRate = data%State%MUD(3)%Q 
                    
                    data%State%MudSystem%TripTankVolumeCalc = min(data%State%MudSystem%TripTankVolumeCalc,50.*42.)      !50. BBL *42. gal/BBL = gal
                    !if TripTankVolumeCalc>50 BBl, excess value(TripTankVolumeCalc-50) is dumped
                    
                    data%State%MudSystem%ActiveTankVolume = min(data%State%MudSystem%ActiveTankVolume , data%Configuration%Mud%ActiveTotalTankCapacityGal - data%Configuration%Mud%ActiveSettledContentsGal)
                    !if ActiveTankVolume is higher, excess amount is dumped                    
                    !write(*,*) 'BellNippleDensity=' , BellNippleDensity
                    
                    !MudWeightOut2 = BellNippleDensity !for drillwatch display
                    !write(*,*) 'MudWeightOut2=' , MudWeightOut2
                    
                    !write(*,*) 
                    
                    
            endif
            
            if (j3 == 0) then
                data%State%MUD(3)%Q=0.0       ! for normal circulation input
                call Set_FlowRate(0d0)
            endif
            

            
!===========================================================================================================================
!===========================================================================================================================              
            
                     
            
            if (j11 > 0 .and. data%State%MudSystem%MudChecked== .true.) then    !BellNippleToWell-NonFullWell    ( FillingWell_By_BellNipple subroutine is called for this state )
                !write(*,*) 'j11 is open'
                data%State%MudSystem%MudChecked= .false.     !to be sure that well is not full after arranging muds
                    !WellToPitsOpen = .TRUE.
                
                !BellNipple flow rate= sum flow rate (well+ mudbucket+ triptank)
                
                !Well to BellNipple: BellNippleVolume
                !MudBucket to BellNipple: BellNippleVolume
                !TripTnak to BellNipple: BellNippleVolume
                
                    data%State%MUD(8)%Q = (data%State%MudSystem%BellNippleVolume/data%State%MudSystem%DeltaT_Mudline)*60.
                    !write(*,*) 'data%State%MUD(8)%Q=' , data%State%MUD(8)%Q
                    
       
                    data%State%MudSystem%BellNippleVolume= data%State%MudSystem%BellNippleVolume- ((data%State%MUD(8)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) ! to be 0.
                    !write(*,*) 'BellNippleVolume-2nd Mode=' , BellNippleVolume   
                    
                    !BellNippleDensity
                    !
                    !
                    !BellNippleDensity , data%State%MUD(8)%Q be code gel dade beshe
                    !shart: j11 > 0 , data%State%MUD(8)%Q > 0.0
                  
                    
            endif
            
            if (j11 == 0) then
                data%State%MUD(8)%Q=0.0       ! for normal circulation input
                !WellToPitsOpen= .false.
            endif
            

            
!===========================================================================================================================
!===========================================================================================================================  
      
            
            
            !WRITE (*,*) 'choke condition', j4, ChokeLineNOTFull
            if (j4 > 0 .and. data%State%MudSystem%ChokeLineNOTFull== .false.) then    !WellToChokeManifold(Through 26)
                !write(*,*) 'j4 is open'
                !write(*,*) 'active by j4'


                    
                    !data%State%MUD(4)%Q= ( Ann_Saved_MudDischarged_Volume_Final+Ann_Kick_Saved_Volume_Final - ((Qlost/60.0d0)*DeltaT_Mudline) )*60.d0/DeltaT_Mudline
                    data%State%MUD(4)%Q= ( data%State%MudSystem%MudVolume_InjectedFromAnn + data%State%MudSystem%Ann_Kick_Saved_Volume )*60.d0/data%State%MudSystem%DeltaT_Mudline    !Injected is referred only to Mud
                    
                    
                    !if ( WellisNOTFull== .true. )       data%State%MUD(4)%Q= 0.0
                    
                    
                    if (j9 > 0) then
                        ChokeLine_FlowCoef= data%Configuration%BopStack%ChokeLineId/(13.625+data%Configuration%BopStack%ChokeLineId)          ! 13.625= BellNipple ID (inch)
                        data%State%MUD(4)%Q= ChokeLine_FlowCoef * data%State%MUD(4)%Q
                    endif                    

                    
                    !call Log_1('data%State%MUD(4)%Q=', data%State%MUD(4)%Q)
                    
                    data%State%MudSystem%ChokeOutletDensity= data%State%MudSystem%ChokeLine_Density%Last()        ! <<< in CirculationCodeSelect Code
                    
                    
                    !MudWeightOut2= ChokeOutletDensity !for drillwatch display
!                    
                    !AnnulusFlowRateFinal: flow from string mud  ,   DeltaVolumeOp: due to trip in 

                
              
                
                
                RealJ4= real(j4)
                    
                    !C71: Active Tank        C77: Trip Tank      C78: ChokeManifoldDump
                    
            if  ( data%State%MudSystem%BellNippleDensity > 1.0) then    
                ! IN ALL CONDITIONS EFFECT OF 78 IS COMPUTED BY RealJ4
                    if (C71==1 .and. C77==0) then  !(volumes in galon) RealJ4: 1 OR 2(IF 78 IS OPEN)

                            IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN
                                
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%ChokeOutletDensity*((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ (((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
                        !write(*,*) 'active increase choke1=' , (((1./RealJ4)*data%State%MUD(4)%Q/60.)*DeltaT_Mudline) 
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)

                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%ChokeOutletDensity > data%State%MudSystem%ActiveTankDensity) THEN

    
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((20.8d0-data%State%MudSystem%ChokeOutletDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)       ! asumed cutting density = 20.8 ppg
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        !write(*,*) 'active increase choke2=' , ((20.8d0-ChokeOutletDensity)/(20.8d0-ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*DeltaT_Mudline) 
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%ChokeOutletDensity < 5.0) THEN                                
                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ ((2.d0-data%State%MudSystem%ChokeOutletDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)       ! asumed GAS density = 2.0 ppg
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        !write(*,*) 'active increase choke3=' ,((2.d0-ChokeOutletDensity)/(2.d0-ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*DeltaT_Mudline)
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%ChokeOutletDensity .and. data%State%MudSystem%ChokeOutletDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                                !write(*,*) ' Auto true 3'

                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ (((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        
                        !write(*,*) 'active increase choke4=' , (((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*DeltaT_Mudline)
                            
                            ENDIF                        
                        
                        
                        
                    endif
                    
                    if (C77==1 .and. C71==0) then       !RealJ4: 1 OR 2(IF 78 IS OPEN)

                            IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN                      
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ChokeOutletDensity*((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ (((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                                         
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%ChokeOutletDensity > data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= ((20.8d0-data%State%MudSystem%ChokeOutletDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)                        
                        
                            
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%ChokeOutletDensity < 5.0) THEN
                                
                        AddedVolumeToTank= ((2.d0-data%State%MudSystem%ChokeOutletDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)        ! asumed GAS density = 2.0 ppg
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                        
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)      
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%ChokeOutletDensity .and. data%State%MudSystem%ChokeOutletDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= (((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline) 
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)  
                                
                            ENDIF                        
                        


                    endif                    
                    
                    if (C71==1 .and. C77==1) then       !RealJ4: 2 OR 3(IF 78 IS OPEN)

                            IF (data%Configuration%Mud%ActiveAutoDensity == .FALSE.) THEN                     
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%ChokeOutletDensity*((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ChokeOutletDensity*((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ (((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ (((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. data%State%MudSystem%ChokeOutletDensity > data%State%MudSystem%ActiveTankDensity) THEN
                                
                                
                        AddedVolumeToTank= ((20.8d0-data%State%MudSystem%ChokeOutletDensity)/(20.8d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                               
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank 
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= ((2.d0-data%State%MudSystem%ChokeOutletDensity)/(2.d0-data%State%MudSystem%ActiveTankDensity))*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)      ! asumed GAS density = 2.0 ppg
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                        
                            ELSEIF (data%Configuration%Mud%ActiveAutoDensity .and. 5.0 < data%State%MudSystem%ChokeOutletDensity .and. data%State%MudSystem%ChokeOutletDensity <= data%State%MudSystem%ActiveTankDensity) THEN
                                
                        AddedVolumeToTank= ((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*AddedVolumeToTank))/(data%State%MudSystem%TripTankVolumeCalc+AddedVolumeToTank)
                                
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ AddedVolumeToTank
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ AddedVolumeToTank 
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1.d0/RealJ4)*data%State%MUD(4)%Q/60.d0)*data%State%MudSystem%DeltaT_Mudline)
                                
                                
                            ENDIF                        
                        

                    endif   
                    
                    
                    if (C71==0 .and. C77==0 .and. C78==1) then       !RealJ4: 1
                            !   autodensity niaz nadarad                          
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ (((1./RealJ4)*data%State%MUD(4)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                    endif
                    

                    
            endif !  if  ( BellNippleDensity > 1.0) then
            
            
                    data%State%MudSystem%TripTankVolumeCalc=min(data%State%MudSystem%TripTankVolumeCalc,50.*42.)      !50. BBL *42. gal/BBL = gal
                    !if TripTankVolumeCalc>50 BBl, excess value(TripTankVolumeCalc-50) is dumped

                    data%State%MudSystem%ActiveTankVolume=min(data%State%MudSystem%ActiveTankVolume , data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)
                    !if ActiveTankVolume is higher, excess amount is dumped                    
                    
            endif 
            
            
            
            
            
            if (j4 == 0 .or. data%State%MudSystem%ChokeLineNOTFull== .true.) then
                !Pressure_BeforeChokes=0.0       ! for normal circulation input
                data%State%MUD(4)%Q=0.0       ! for CirculationCodeSelect input.
            endif
            
            
            if (j4 > 0) then
                data%State%MudSystem%WellToChokeManifoldOpen= .true.
            else
                data%State%MudSystem%WellToChokeManifoldOpen= .false.
            endif
   
!===========================================================================================================================
!===========================================================================================================================  
            
            if (j18 > 0) then    !StandPipeManifoldToChokeManifold-Through ChokeLine
                !write(*,*) 'j18 is open'
                !write(*,*) 'active by j18'
                
!  STEP 1: REDUCTION FROM PUMPS     STEP 1: REDUCTION FROM PUMPS    STEP 1: REDUCTION FROM PUMPS  (SAME TO PumpsToString LINE)              
           ! (NOT NEEDED)
                
                
                
!  STEP 2: ADD TO TANKS     STEP 2: ADD TO TANKS    STEP 2: ADD TO TANKS    STEP 2: ADD TO TANKS  (SAME TO WellToChokeManifold LINE)              
                
                !Pump1toCh:             PumpsToChokeManifold Coefficient
                !Jj2,Jj12,Jj13:    TanksToMudPump Coefficient
                !H:             Pumps To Tank_Through65 or 67 Coefficient  

            data%State%MUD(9)%Q= jj2*(1-H82)*(1-DumpPump1)*Pump1toCh*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*(1-DumpPump2)*Pump2toCh*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*(1-DumpCementPump)*Pump3toCh*data%State%Pump(3)%Flow_Rate
                
            
            
            Denominator_a= (jj2*(1.-H82)*(1.-DumpPump1)*Pump1toCh*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*Pump2toCh*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*Pump3toCh*data%State%Pump(3)%Flow_Rate)
            
            if (Denominator_a /= 0.) then
        data%State%MudSystem%Density_Ch= (jj2*(1.-H82)*(1.-DumpPump1)*Pump1toCh*data%State%MudSystem%Mp1Density*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*Pump2toCh*data%State%MudSystem%Mp2Density*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*Pump3toCh*data%State%MudSystem%Mp3Density*data%State%Pump(3)%Flow_Rate)/ & 
                                        Denominator_a
            !write(*,*) 'Density_Ch=' , Density_Ch
        !    
        !    else
        !Density_Ch= 0.0
            endif   
            
            
                RealJ18= M71+M77+M78
                    
                    !C71: Active Tank        C77: Trip Tank      C78: ChokeManifoldDump
                    
                
                ! IN ALL CONDITIONS EFFECT OF 78 IS COMPUTED BY RealJ18
                    if (M71==1 .and. M77==0) then  !(volumes in galon) RealJ18: 1 OR 2(IF 78 IS OPEN)
            
                            !  autodensity niaz nadarad            
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%Density_Ch*((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ (((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
            
                    endif
                    
                    if (M77==1 .and. M71==0) then       !RealJ18: 1 OR 2(IF 78 IS OPEN)
            
                            !  autodensity niaz nadarad                         
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%Density_Ch*((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ (((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
            
                    endif                    
                    
                    if (M71==1 .and. M77==1) then       !RealJ18: 2 OR 3(IF 78 IS OPEN)
            
                            !  autodensity niaz nadarad                       
                        data%State%MudSystem%ActiveTankDensity= ((data%State%MudSystem%ActiveTankDensity*data%State%MudSystem%ActiveTankVolume)+(data%State%MudSystem%Density_Ch*((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%ActiveTankVolume+(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%Density_Ch*((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume+ (((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc+ (((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline) 
                        
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ C78*(((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
            
                    endif   
                    
                    
                    if (M71==0 .and. M77==0 .and. M78==1) then       !RealJ18: 1
                            !   autodensity niaz nadarad                          
                        data%State%MudSystem%ChokeManifoldDumpVolume= data%State%MudSystem%ChokeManifoldDumpVolume+ (((1./RealJ18)*data%State%MUD(9)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                    endif
                    
            
            
                    
                    
                    
            
            
                    data%State%MudSystem%TripTankVolumeCalc=min(data%State%MudSystem%TripTankVolumeCalc,50.*42.)      !50. BBL *42. gal/BBL = gal
                    !if TripTankVolumeCalc>50 BBl, excess value(TripTankVolumeCalc-50) is dumped
            
                    data%State%MudSystem%ActiveTankVolume=min(data%State%MudSystem%ActiveTankVolume , data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)
                    !if ActiveTankVolume is higher, excess amount is dumped                    
                    
            endif 
            
            
            if (j18 == 0) then
                data%State%MUD(9)%Q=0.0
            endif            
            
            
!===========================================================================================================================
!===========================================================================================================================               
            
            if (j5 > 0 .and. (data%State%MudSystem%ActiveTankVolume/data%State%MudSystem%ActiveTankFloorArea) > (data%State%MudSystem%TripTankVolumeCalc/data%State%MudSystem%TripTankFloorArea)) then    !ActiveTankToTripTank
                ! second condition is for Utube flow
                !write(*,*) 'j5 is open'
                
                !   ActiveTankVolume/ActiveTankFloorArea... means tank height
                data%State%MUD(5)%Q= 300.       ! constant flow rate(gpm)
                

                    data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume - ((data%State%MUD(5)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)
                    data%State%MudSystem%TripTankVolumeCalc= data%State%MudSystem%TripTankVolumeCalc + ((data%State%MUD(5)%Q/60.)*data%State%MudSystem%DeltaT_Mudline)                        
                             
                    data%State%MudSystem%TripTankDensityCalc= ((data%State%MudSystem%TripTankDensityCalc*data%State%MudSystem%TripTankVolumeCalc)+(data%State%MudSystem%ActiveTankDensity*(data%State%MUD(5)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))/(data%State%MudSystem%TripTankVolumeCalc+((data%State%MUD(5)%Q/60.)*data%State%MudSystem%DeltaT_Mudline))
                        
  
                    
                    data%State%MudSystem%TripTankVolumeCalc=min(data%State%MudSystem%TripTankVolumeCalc,50.*42.)      !50. BBL *42. gal/BBL = gal
                    !if TripTankVolumeCalc>50, excess value(TripTankVolumeCalc-50) is dumped                
                
            endif
            
            if (j5 == 0) then
                data%State%MUD(5)%Q=0.0
            endif 
            
!===========================================================================================================================
!===========================================================================================================================                 

            if (j16 > 0) then    !PathsToGauge75
                
                if (K79 == 1) then
                    
                    data%State%MudSystem%PressureGauge75= data%State%PressureDisplay%PressureGauges(1)    !String to Gauge75
                    
                elseif (K82 == 1 .and. k83 == 0 .and. k84 == 0 .and. k78 == 0) then
                    data%State%MudSystem%PressureGauge75= PumpPressure1 
                elseif (K82 == 0 .and. k83 == 1 .and. k84 == 0 .and. k78 == 0) then
                    data%State%MudSystem%PressureGauge75= PumpPressure2
                elseif (K82 == 0 .and. k83 == 0 .and. k84 == 1 .and. k78 == 0) then
                    data%State%MudSystem%PressureGauge75= PumpPressure3 
                elseif (K82 == 0 .and. k83 == 0 .and. k84 == 0 .and. k78 == 1) then
                    data%State%MudSystem%PressureGauge75= 0.
                endif
            
                !if (K82 == 1) PressureGauge75= PumpPressure1        !Pump1 to Gauge75'
                !if (K83 == 1) PressureGauge75= PumpPressure2        !Pump2 to Gauge75
                !if (K84 == 1) PressureGauge75= PumpPressure3        !Pump3 to Gauge75
                !if (K78 == 1) PressureGauge75= 0.                   !Dump to Gauge75
                
            endif
            

            data%EquipmentControl%StandPipeManifold%StandPipeGauge1= (1 - data%State%MudSystem%StandPipeGauge1Malf) * data%State%MudSystem%PressureGauge75    ! for STManifold Display
            !write(*,*) 'PressureGauge75=' , PressureGauge75
            !P1toSt= jj2*(1-H82)*(1-DumpPump1)*G82
            !P2toSt= jj12*(1-H83)*(1-DumpPump2)*G83
            !CptoSt= jj13*(1-H84)*(1-DumpCementPump)*G84
!===========================================================================================================================
!===========================================================================================================================             

            if (j17 > 0) then    !PumpsToGauge76
                
                if (L79 == 1) then
                    
                    data%State%MudSystem%PressureGauge76= data%State%PressureDisplay%PressureGauges(1)    !String to Gauge76
                    
                elseif (L82 == 1 .and. L83 == 0 .and. L84 == 0 .and. L78 == 0) then
                    data%State%MudSystem%PressureGauge76= PumpPressure1
                elseif (L82 == 0 .and. L83 == 1 .and. L84 == 0 .and. L78 == 0) then
                    data%State%MudSystem%PressureGauge76= PumpPressure2
                elseif (L82 == 0 .and. L83 == 0 .and. L84 == 1 .and. L78 == 0) then
                    data%State%MudSystem%PressureGauge76= PumpPressure3
                elseif (L82 == 0 .and. L83 == 0 .and. L84 == 0 .and. L78 == 1) then
                    data%State%MudSystem%PressureGauge76= 0.
                endif                

                
                !if (L79 == 1) PressureGauge76= PressureGauges(1)    !String to Gauge76
                !if (L82 == 1) PressureGauge76= PumpPressure1        !Pump1 to Gauge76
                !if (L83 == 1) PressureGauge76= PumpPressure2        !Pump2 to Gauge76
                !if (L84 == 1) PressureGauge76= PumpPressure3        !Pump3 to Gauge76
                !if (L78 == 1) PressureGauge76= 0.                   !Dump to Gauge76
                
            endif
            data%EquipmentControl%StandPipeManifold%StandPipeGauge2= (1 - data%State%MudSystem%StandPipeGauge2Malf) * data%State%MudSystem%PressureGauge76    ! for STManifold Display
!===========================================================================================================================
!===========================================================================================================================              
           !
           !if (PressureGauge75 == PressureGauges(1))  then  ! means: 75 goes to string
           !    PumpPressureDW= PressureGauges(1)  !for DrillWatch Display
           !    CALL Set_StandPipePressure(real(PressureGauges(1) , 8))    !for Data Display Console
           !endif
           !
           !
           !if (PressureGauge76 == PressureGauges(1))  then  ! means: 76 goes to string
           !    PumpPressureDW= PressureGauges(1)  !for DrillWatch Display
           !    CALL Set_StandPipePressure(real(PressureGauges(1) , 8))    !for Data Display Console
           !endif
           !
           !if (PressureGauge75 /= PressureGauges(1) .and. PressureGauge76 /= PressureGauges(1))  then  ! means: non of gauges go to string
           !    PumpPressureDW= max(PressureGauge75,PressureGauge76)  !for DrillWatch Display
           !    !StandPipePressureGauge= max(PressureGauge75,PressureGauge76)    !for Data Display Console
           !    CALL Set_StandPipePressure(real(max(PressureGauge75,PressureGauge76) , 8))    !for Data Display Console
           !endif
          !write(*,*) 'TapSelector=' , TapSelector
            
            
        if (data%State%StudentStation%TapSelector == .false.) then
            
                data%EquipmentControl%DrillingWatch%PumpPressure= data%State%MudSystem%PressureGauge75  !for DrillWatch Display
               CALL Set_StandPipePressure(real((1-data%State%MudSystem%DrillPipePressureMalf)*data%State%MudSystem%PressureGauge75 , 8))    !for Data Display Console
        else
                data%EquipmentControl%DrillingWatch%PumpPressure= data%State%MudSystem%PressureGauge76  !for DrillWatch Display
               CALL Set_StandPipePressure(real((1-data%State%MudSystem%DrillPipePressureMalf)*data%State%MudSystem%PressureGauge76 , 8))    !for Data Display Console
        endif
    
!===========================================================================================================================
!===========================================================================================================================  
            ! SHOULD BE AT LAST TO HAVE THE CORRECT DENSITIES FOR Suction_Density_MudSystem
            
            if (j2 > 0) then    !TanksToMudPump1

                
                    !Relief= 0: deactive 1: active              data%State%Pump(1)%Flow_Rate   , data%State%Pump(2)%Flow_Rate
                    

                    RealJ2= real(j2)
                    
                    if (A71==1 .and. (data%State%MudSystem%ActiveTankVolume-(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        A71= 0
                        RealJ2= RealJ2-1
                        write(*,*) 'ActiveTank Level Warning'
                        call Activate_ActiveTankUnderVolume()
                    endif
                    
                    if (A72==1 .and. (data%State%MudSystem%ReserveTankVolume-(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        A72= 0
                        RealJ2= RealJ2-1
                        write(*,*) 'ReserveTank Level Warning'
                    endif
                    
                    if (A71==3 .and. (data%State%MudSystem%CementTankVolumeCalc-(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        A73= 0
                        RealJ2= RealJ2-1
                        write(*,*) 'CementTank Level Warning'
                    endif                    
                    
                    
                    if(RealJ2> 0.0) then
                    
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume- A71*(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%ReserveTankVolume= data%State%MudSystem%ReserveTankVolume- A72*(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%CementTankVolumeCalc= data%State%MudSystem%CementTankVolumeCalc- A73*(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        !write(*,*) 'Active-decline=' , A71*(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*DeltaT_Mudline)
                        total_decrease= total_decrease+ A71*(((1./RealJ2)*data%State%Pump(1)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                    if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
                        total_decrease= 0.
                    endif   
                        !write(*,*) 'total_decrease=' , total_decrease
                        
                        
                        data%State%MudSystem%Mp1Density= (A71*data%State%MudSystem%ActiveTankDensity+A72*data%State%MudSystem%ReserveTankDensity+A73*data%State%MudSystem%CementTankDensityCalc)/RealJ2
                    else
                        write(*,*) 'stop'
                    endif
                    

                    
            endif

 
!===========================================================================================================================
!===========================================================================================================================  
            ! SHOULD BE AT LAST TO HAVE THE CORRECT DENSITIES FOR Suction_Density_MudSystem
            
            if (j12 > 0) then    !TanksToMudPump2

                
                    !Relief= 0: deactive 1: active              data%State%Pump(1)%Flow_Rate   , data%State%Pump(2)%Flow_Rate

                    RealJ12= real(J12)
                    
                    if (E71==1 .and. (data%State%MudSystem%ActiveTankVolume-(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        E71= 0
                        RealJ12= RealJ12-1
                        write(*,*) 'ActiveTank Level Warning'
                    endif
                    
                    if (E72==1 .and. (data%State%MudSystem%ReserveTankVolume-(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        E72= 0
                        RealJ12= RealJ12-1
                        write(*,*) 'ReserveTank Level Warning'
                    endif
                    
                    if (E71==3 .and. (data%State%MudSystem%CementTankVolumeCalc-(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        E73= 0
                        RealJ12= RealJ12-1
                        write(*,*) 'CementTank Level Warning'
                    endif                    
                    
                    
                    if(RealJ12> 0.0) then
                    
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume- E71*(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%ReserveTankVolume= data%State%MudSystem%ReserveTankVolume- E72*(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%CementTankVolumeCalc= data%State%MudSystem%CementTankVolumeCalc- E73*(((1/RealJ12)*data%State%Pump(2)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)

                        
                        
                        data%State%MudSystem%Mp2Density= (E71*data%State%MudSystem%ActiveTankDensity+E72*data%State%MudSystem%ReserveTankDensity+E73*data%State%MudSystem%CementTankDensityCalc)/RealJ12
                    else
                        write(*,*) 'stop'
                    endif
                    
                    
            endif
            
            
!===========================================================================================================================
!===========================================================================================================================  
            ! SHOULD BE AT LAST TO HAVE THE CORRECT DENSITIES FOR Suction_Density_MudSystem
            
            if (j13 > 0) then    !TanksToCementPump

                
                    !Relief= 0: deactive 1: active              data%State%Pump(1)%Flow_Rate   , data%State%Pump(2)%Flow_Rate
                

                    RealJ13= real(J13)
                    
                    if (F71==1 .and. (data%State%MudSystem%ActiveTankVolume-(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        F71= 0
                        RealJ13= RealJ13-1
                        write(*,*) 'ActiveTank Level Warning'
                    endif
                    
                    if (F72==1 .and. (data%State%MudSystem%ReserveTankVolume-(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        F72= 0
                        RealJ13= RealJ13-1
                        write(*,*) 'ReserveTank Level Warning'
                    endif
                    
                    if (F71==3 .and. (data%State%MudSystem%CementTankVolumeCalc-(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)) < 0.0) then
                        F73= 0
                        RealJ13= RealJ13-1
                        write(*,*) 'CementTank Level Warning'
                    endif                    
                    
                    
                    if(RealJ13> 0.0) then
                    
                        data%State%MudSystem%ActiveTankVolume= data%State%MudSystem%ActiveTankVolume- F71*(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%ReserveTankVolume= data%State%MudSystem%ReserveTankVolume- F72*(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        data%State%MudSystem%CementTankVolumeCalc= data%State%MudSystem%CementTankVolumeCalc- F73*(((1/RealJ13)*data%State%Pump(3)%Flow_Rate/60.)*data%State%MudSystem%DeltaT_Mudline)
                        
                        
                        data%State%MudSystem%Mp3Density= (F71*data%State%MudSystem%ActiveTankDensity+F72*data%State%MudSystem%ReserveTankDensity+F73*data%State%MudSystem%CementTankDensityCalc)/RealJ13
                    else
                        write(*,*) 'stop'
                    endif                    
                    
                    
            endif
                        

            
!===========================================================================================================================
!=========================================================================================================================== 
            ! SHOULD BE AT LAST TO HAVE THE CORRECT DENSITIES FOR Suction_Density_MudSystem
            
            if (j14 > 0) then    !PumpsToString         Suction_Density_MudSystem is used for Mud Circulation Code 
                !write(*,*) 'j14 is open'
                !call Log_1('j14 is open')
                
                ! << if H82 or H83 or H4 are open, no flow goes to other parts of system >>
                
                ! pump flow rate1 be sharti be samte string miravad ke masire j2 bar gharar bashad
                ! pump flow rate2 be sharti be samte string miravad ke masire j12 bar gharar bashad
                ! pump flow rate3 be sharti be samte string miravad ke masire j13 bar gharar bashad
                
                !G:             PumpsToString Coefficient
                !Jj2,Jj12,Jj13:    TanksToMudPump Coefficient
                !H:             Pumps To Tank_Through65 or 67 Coefficient
                !
                !write(*,*) 'jj2=' , jj2
                !write(*,*) 'jj12=' , jj12
                !write(*,*) 'jj13=' , jj13
                !write(*,*) 'H82=' , H82
                !write(*,*) 'H83=' , H83
                !write(*,*) 'H84=' , H84
                !write(*,*) 'DumpPump1=' , DumpPump1
                !write(*,*) 'DumpPump2=' , DumpPump2
                !write(*,*) 'DumpCementPump=' , DumpCementPump
                !write(*,*) 'G82=' , G82
                !write(*,*) 'G83=' , G83
                !write(*,*) 'G84=' , G84
                !write(*,*) 'Mp1Density=' , Mp1Density
                !write(*,*) 'Mp2Density=' , Mp2Density
                !write(*,*) 'Mp3Density=' , Mp3Density
                !
                !

                

                !PumpsDumpVolume= PumpsDumpVolume+    jj2*(1-H82)*DumpPump1*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*DumpPump2*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*DumpCementPump*data%State%Pump(3)%Flow_Rate
                
            Denominator= (jj2*(1.-H82)*(1.-DumpPump1)*G82*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*G83*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*G84*data%State%Pump(3)%Flow_Rate)
            
            if (Denominator /= 0.) then
        data%State%MudSystem%Suction_Density_MudSystem= (jj2*(1.-H82)*(1.-DumpPump1)*G82*data%State%MudSystem%Mp1Density*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*G83*data%State%MudSystem%Mp2Density*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*G84*data%State%MudSystem%Mp3Density*data%State%Pump(3)%Flow_Rate)/ & 
                                        Denominator
            endif
            
            data%State%MudSystem%CompressedMudDensity= data%State%MudSystem%Suction_Density_MudSystem
                    
            data%EquipmentControl%DrillingWatch%MudWeightIn=  data%State%MudSystem%Suction_Density_MudSystem  !for drillwatch display
            
            
            data%State%MUD(2)%Q= jj2*(1-H82)*(1-DumpPump1)*G82*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*(1-DumpPump2)*G83*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*(1-DumpCementPump)*G84*data%State%Pump(3)%Flow_Rate
                
            !write(*,*) 'data%State%MUD(2)%Q=' , data%State%MUD(2)%Q
            
            
            
            !jj2*(1-H82)*(1-DumpPump1)*G82    :if ==1, Pump1 to String is open
            !jj12*(1-H83)*(1-DumpPump2)*G83   :if ==1, Pump2 to String is open
            !jj13*(1-H84)*(1-DumpCementPump)*G84  :if ==1, Cement to String is open

     
            
            endif      
            
            if (j14 == 0) then        ! for normal circulation input 
                data%State%MUD(2)%Q=0.0
                !PumpPressure1= 0.0
                !PumpPressure2= 0.0
                !PumpPressure3= 0.0
            endif
            
            
            
!===========================================================================================================================
!===========================================================================================================================             

            if (j19 > 0 .and. data%State%MudSystem%MudChecked== .true.) then    !PumpsToWell_KillLine         Suction_Density_PumpsToWell is used for Mud Circulation Code 
                !write(*,*) 'j19 is open'
                data%State%MudSystem%MudChecked= .false.     !to be sure that well is not full after arranging muds

                ! << if H82 or H83 or H4 are open, no flow goes to other parts of system >>
                
                ! pump flow rate1 be sharti be samte well miravad ke masire j2 bar gharar bashad
                ! pump flow rate2 be sharti be samte well miravad ke masire j12 bar gharar bashad
                ! pump flow rate3 be sharti be samte well miravad ke masire j13 bar gharar bashad
                
                !G:             PumpsToString Coefficient
                !Jj2,Jj12,Jj13:    TanksToMudPump Coefficient
                !H:             Pumps To Tank_Through65 or 67 Coefficient
                !
                !write(*,*) 'jj2=' , jj2
                !write(*,*) 'jj12=' , jj12
                !write(*,*) 'jj13=' , jj13
                !write(*,*) 'H82=' , H82
                !write(*,*) 'H83=' , H83
                !write(*,*) 'H84=' , H84
                !write(*,*) 'DumpPump1=' , DumpPump1
                !write(*,*) 'DumpPump2=' , DumpPump2
                !write(*,*) 'DumpCementPump=' , DumpCementPump
                !write(*,*) 'G82=' , G82
                !write(*,*) 'G83=' , G83
                !write(*,*) 'G84=' , G84
                !write(*,*) 'Mp1Density=' , Mp1Density
                !write(*,*) 'Mp2Density=' , Mp2Density
                !write(*,*) 'Mp3Density=' , Mp3Density
                !
                !

                

                !PumpsDumpVolume= PumpsDumpVolume+    jj2*(1-H82)*DumpPump1*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*DumpPump2*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*DumpCementPump*data%State%Pump(3)%Flow_Rate
                
            Denominator= (jj2*(1.-H82)*(1.-DumpPump1)*N82*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*N83*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*N84*data%State%Pump(3)%Flow_Rate)
            
            if (Denominator /= 0.) then
        data%State%MudSystem%Suction_Density_PumpsToWell= (jj2*(1.-H82)*(1.-DumpPump1)*N82*data%State%MudSystem%Mp1Density*data%State%Pump(1)%Flow_Rate + jj12*(1.-H83)*(1.-DumpPump2)*N83*data%State%MudSystem%Mp2Density*data%State%Pump(2)%Flow_Rate + jj13*(1.-H84)*(1.-DumpCementPump)*N84*data%State%MudSystem%Mp3Density*data%State%Pump(3)%Flow_Rate)/ & 
                                        Denominator
            endif
                
                    

            
            
            data%State%MUD(10)%Q= jj2*(1-H82)*(1-DumpPump1)*N82*data%State%Pump(1)%Flow_Rate + jj12*(1-H83)*(1-DumpPump2)*N83*data%State%Pump(2)%Flow_Rate + jj13*(1-H84)*(1-DumpCementPump)*N84*data%State%Pump(3)%Flow_Rate
                



     
            
            endif      
            
            if (j19 == 0) then        ! for normal circulation input 
                data%State%MUD(10)%Q=0.0
                !PumpPressure1= 0.0
                !PumpPressure2= 0.0
                !PumpPressure3= 0.0
            endif
!===========================================================================================================================
!===========================================================================================================================             
            
            
            
!AnnulusFlowRateFinal = 0.d0  ! this is a reset for calculated flow rate in UTUBES,TRIPIN,TRIPOUT codes         
            
            
            
            
            
            
            
            
            
            
            
            
            
!!====================================================================== 
!!                  Well Head Condition Determination
!!======================================================================             
            
            
        if ( data%State%MudSystem%WellToChokeManifoldOpen .or. data%State%MudSystem%WellToPitsOpen) then
            data%State%MudSystem%WellHeadIsOpen= .true.
        else
            data%State%MudSystem%WellHeadIsOpen= .false.
        endif
        
            
    
            
            
            
            
!!====================================================================== 
!!                              WARNINGS
!!======================================================================              
            
            
        IF (Manifold%Valve(65)%Status == .TRUE.) call Activate_Pump1PopOffValveBlown()  !Pump1PopOffValveBlown= .TRUE.
        IF (Manifold%Valve(66)%Status == .TRUE.) call Activate_Pump2PopOffValveBlown() ! Pump2PopOffValveBlown= .TRUE.        
        IF (Manifold%Valve(67)%Status == .TRUE.) call Activate_Pump3PopOffValveBlown()  !Pump2PopOffValveBlown= .TRUE.
        
            
        IF (data%State%MudSystem%ActiveTankVolume >= (data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)) THEN
            data%State%MudSystem%ActiveTankVolume = (data%Configuration%Mud%ActiveTotalTankCapacityGal-data%Configuration%Mud%ActiveSettledContentsGal)
            call Activate_ActiveTankOverflow()
        ELSE
            call Deactivate_ActiveTankOverflow()
        ENDIF
        
           
            
!!====================================================================== 
!!          UPDATING TANKS DENSITIES & Volumes FOR MUD CIRCULATION
!!======================================================================  
        
        !write(*,*) 'ReserveTankVolume=' , real(ReserveTankVolume)
        
            call Set_ActiveMudVolume_StudentStation(real(data%State%MudSystem%ActiveTankVolume/42.,8))   ! 42: gal to bbl
            call Set_ActiveDensity_StudentStation(real(data%State%MudSystem%ActiveTankDensity,8))
            call Set_ReserveMudVolume_StudentStation(real(data%State%MudSystem%ReserveTankVolume/42.,8))   ! 42: gal to bbl
            call Set_ReserveDensity_StudentStation(real(data%State%MudSystem%ReserveTankDensity,8))
            data%EquipmentControl%DrillingWatch%KillMudVolume= data%State%MudSystem%ReserveTankVolume/42.   ! for DrillWatch
            !PitGainLose= 


!!====================================================================== 
!!                           DRILLING DATA DISPLAY
!!======================================================================          
         
         
        IF (data%EquipmentControl%DataDisplayConsole%TotalStrokeCounterResetSwitch == 1) then        !for drilling data display
            data%State%MudSystem%TotalStrokesPump1=0.
            data%State%MudSystem%TotalStrokesPump2=0.
        ENDIF
 
            data%State%MudSystem%TotalStrokesPump1=data%State%MudSystem%TotalStrokesPump1+((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline        !for drilling data display
            data%State%MudSystem%TotalStrokesPump2=data%State%MudSystem%TotalStrokesPump2+((data%EquipmentControl%DataDisplayConsole%MP2SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline        !for drilling data display
            data%State%MudSystem%GraphTotalStrokes=data%State%MudSystem%GraphTotalStrokes+((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline+((data%EquipmentControl%DataDisplayConsole%MP2SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline
     
            
            data%State%MPumps%Total_Stroke_Counter_For_Plot = data%State%MPumps%Total_Stroke_Counter_For_Plot + ((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge + data%EquipmentControl%DataDisplayConsole%MP2SPMGauge) / 60.0) * data%State%MudSystem%DeltaT_Mudline
        
            ! CALL SetTotalStrokes(INT(data%State%MPumps%Total_Stroke_Counter_For_Plot))
            
         data%EquipmentControl%DataDisplayConsole%TotalStrokeCounter= real(nint(data%State%MudSystem%TotalStrokesPump1+data%State%MudSystem%TotalStrokesPump2))        !for drilling data display        
        
!===========================================================================
!                        	MUD PUMP STROKES
!                            & TOTAL STROKE- CHOKE CONTROL PANEL
!=========================================================================== 
         !write(*,*) 'a)))' , ChokePanelStrokeResetSwitch
          if (data%EquipmentControl%ChokeControlPanel%ChokePanelStrokeResetSwitch == 1) then
              IF (data%EquipmentControl%ChokeControlPanel%ChokePanelPumpSelectorSwitch == 1) THEN
                  !write(*,*) '1 reset'
                  data%State%Choke%TotalStrokes1 =0.
              elseif (data%EquipmentControl%ChokeControlPanel%ChokePanelPumpSelectorSwitch == 2) THEN
                  !write(*,*) '2 reset'
                  data%State%Choke%TotalStrokes2 =0.
              else
                  !write(*,*) 'both reset'
                  
                  data%State%Choke%TotalStrokes1 =0.
                  data%State%Choke%TotalStrokes2 =0.
              endif
          endif
          
         !write(*,*) 'b)))' , ChokePanelStrokeResetSwitch
    
       
            data%State%Choke%TotalStrokes1= data%State%Choke%TotalStrokes1+((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline       
            data%State%Choke%TotalStrokes2= data%State%Choke%TotalStrokes2+((data%EquipmentControl%DataDisplayConsole%MP2SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline      
       
     
       
            IF (data%EquipmentControl%ChokeControlPanel%ChokePanelPumpSelectorSwitch == 1) THEN
                data%EquipmentControl%ChokeControlPanel%ChokePanelSPMCounter = real(nint(data%EquipmentControl%DataDisplayConsole%MP1SPMGauge))
                data%EquipmentControl%ChokeControlPanel%ChokePanelTotalStrokeCounter = real(nint(data%State%Choke%TotalStrokes1))
            ELSEIF (data%EquipmentControl%ChokeControlPanel%ChokePanelPumpSelectorSwitch == 2) THEN
                data%EquipmentControl%ChokeControlPanel%ChokePanelSPMCounter = real(nint(data%EquipmentControl%DataDisplayConsole%MP2SPMGauge))
                data%EquipmentControl%ChokeControlPanel%ChokePanelTotalStrokeCounter = real(nint(data%State%Choke%TotalStrokes2))
            ELSE
                data%EquipmentControl%ChokeControlPanel%ChokePanelSPMCounter= real(nint(data%EquipmentControl%DataDisplayConsole%MP1SPMGauge+data%EquipmentControl%DataDisplayConsole%MP2SPMGauge))
                data%EquipmentControl%ChokeControlPanel%ChokePanelTotalStrokeCounter = real(nint(data%State%Choke%TotalStrokes1+data%State%Choke%TotalStrokes2))
            ENDIF
            
  !  ChokePanelStrokeResetSwitch = 0     
!======================================================================        
        
!!====================================================================== 
!!               MUD VOLUME TOTALIZER DISPLAY VALUES
!!====================================================================== 
            
        
    data%EquipmentControl%DrillingWatch%PitVolume= data%State%MudSystem%ActiveTankVolume/42.d0     !(bbl) For DrillWatch Display
    
    !write(*,*) 'PitVolume,ActiveTankVolume=' ,PitVolume,ActiveTankVolume
    
    
    data%State%MudSystem%MudTank1_vol= data%State%MudSystem%ActiveTankVolume/3.   ! (gal)
    data%State%MudSystem%MudTank2_vol= data%State%MudSystem%ActiveTankVolume/3.   ! (gal)
    data%State%MudSystem%MudTank3_vol= data%State%MudSystem%ActiveTankVolume/3.   ! (gal) 
    data%State%MudSystem%MudTank4_vol= data%State%MudSystem%TripTankVolumeCalc
    

    
    
    
      IF (data%EquipmentControl%DataDisplayConsole%MVTPowerSwitch==1) THEN     
         data%EquipmentControl%DataDisplayConsole%MudTanksVolumeGauge= (1 - data%State%MudSystem%MudTanksVolumeGaugeMalf) *((data%State%MudSystem%MudTank1_vol*data%EquipmentControl%DataDisplayConsole%MudTank1Switch)+(data%State%MudSystem%MudTank2_vol*data%EquipmentControl%DataDisplayConsole%MudTank2Switch)+ &
                            (data%State%MudSystem%MudTank3_vol*data%EquipmentControl%DataDisplayConsole%MudTank3Switch)+(data%State%MudSystem%MudTank4_vol*data%EquipmentControl%DataDisplayConsole%MudTank4Switch)+data%State%MudSystem%ActiveTankSettled) !(gal)
     ELSEIF (data%EquipmentControl%DataDisplayConsole%MVTPowerSwitch==0) THEN
         data%EquipmentControl%DataDisplayConsole%MudTanksVolumeGauge= (1 - data%State%MudSystem%MudTanksVolumeGaugeMalf) *0.
     ENDIF     
            
!!====================================================================== 
!!                           MUD VOLUME TOTALIZER
!!======================================================================
     



    !  IF (data%EquipmentControl%DataDisplayConsole%MVTPowerSwitch==1 .and. IsPortable==.false.) THEN     
         

     
    !      IF (data%EquipmentControl%DataDisplayConsole%MVTSetAlarmSwitch==0) THEN
     
    !             data%EquipmentControl%DataDisplayConsole%PitGainLossGauge= ( ((ActiveTankVolume/42.) - RefrencePitVolume))  - PitGainLossGaugeMalf*(( ((ActiveTankVolume/42.) - RefrencePitVolume))+50)       !(bbl)          
         
    !      ELSEIF (data%EquipmentControl%DataDisplayConsole%MVTSetAlarmSwitch==-1) THEN
             
             
    !          MVT_MinVol_Allowded= PitGainLossZero+ MIN(0.,(data%EquipmentControl%DataDisplayConsole%MVTSetAlarmLowKnob-50))-0.1
    !          data%EquipmentControl%DataDisplayConsole%PitGainLossGauge= MVT_MinVol_Allowded  - PitGainLossGaugeMalf*(MVT_MinVol_Allowded+50)
    !          !    - PitGainLossGaugeMalf*(MVT_MinVol_Allowded+50) : Malf effect
    !          !PitGainLose=(MVT_MinVol_Allowded)    ! DrillWatch       (incorrect)
    !          !RefrencePitVolume= ActiveTankVolume/42.    !(bbl)
             
    !      ELSE   !(MVTSetAlarmSwitch==1)
             
    !          MVT_MaxVol_Allowded= PitGainLossZero+ MAX(0., (data%EquipmentControl%DataDisplayConsole%MVTSetAlarmHighKnob-50.))+0.1
    !          data%EquipmentControl%DataDisplayConsole%PitGainLossGauge= MVT_MaxVol_Allowded   - PitGainLossGaugeMalf*(MVT_MaxVol_Allowded+50)
    !          !    - PitGainLossGaugeMalf*(MVT_MaxVol_Allowded+50) : Malf effect
    !          !PitGainLose=(MVT_MaxVol_Allowded)    ! DrillWatch       (incorrect)
    !          !RefrencePitVolume= ActiveTankVolume/42.    !(bbl)
    !      ENDIF     
     
    !     !PitGainLossZero_Old= PitGainLossZero
    !     !MVTCoarseKnob_Old= MVTCoarseKnob
    !     !MVTFineKnob_Old= MVTFineKnob
    !     !FirstSet_Time= .false.
        
        
         
    !      IF ( ActiveTankVolume/42. < (RefrencePitVolume-ABS(MVT_MinVol_Allowded)) .OR. ActiveTankVolume/42. > (RefrencePitVolume+ABS(MVT_MaxVol_Allowded)) ) THEN
             
    !          data%EquipmentControl%DataDisplayConsole%MVTAlarmLED = 1 !(blinking)
    !          IF (data%EquipmentControl%DataDisplayConsole%MVTHornSwitch) THEN
    !              data%EquipmentControl%DataDisplayConsole%Buzzer2= .TRUE.
    !          ELSE
    !              data%EquipmentControl%DataDisplayConsole%Buzzer2= .FALSE.
    !          ENDIF
             
    !      ELSE
    !          data%EquipmentControl%DataDisplayConsole%MVTAlarmLED = 0   !(OFF)
    !          data%EquipmentControl%DataDisplayConsole%Buzzer2= .false.
    !      ENDIF  
         
         
         
    !  ELSEIF (data%EquipmentControl%DataDisplayConsole%MVTPowerSwitch==0) THEN
    !      !MudTanksVolumeGauge= 0.
    !      data%EquipmentControl%DataDisplayConsole%PitGainLossGauge= -50
    !      data%EquipmentControl%DataDisplayConsole%MVTAlarmLED= 0
    !      data%EquipmentControl%DataDisplayConsole%Buzzer2= .false.
        
    
    !  ENDIF
     
!!====================================================================== 
!!                           RETURN CALCULATIONS
!!======================================================================      
     

     
     
        data%EquipmentControl%DrillingWatch%PercentFlow= (data%State%MudSystem%ReturnFlowRate/data%State%MudSystem%PedalMeter) *100.  !(percent)  ! for DrillWatch display
        if (abs(data%EquipmentControl%DrillingWatch%PercentFlow - unityreturn) > 1.0) then
        
           write(*,*) 'PercentFlow,ReturnFlowRate,PedalMeter=' , data%EquipmentControl%DrillingWatch%PercentFlow,data%State%MudSystem%ReturnFlowRate,data%State%MudSystem%PedalMeter
           write(*,*) 'unityreturn=' , unityreturn
        endif
    
     
         ! ReturnFlowRate=800. set in startup as initial value
        data%State%MudSystem%ReturnFlowPercent= (data%State%MudSystem%ReturnFlowRate/data%State%MudSystem%PedalMeter) *100.  !(percent)  
        !write(*,*) 'ReturnFlowPercent,ReturnFlowRate=' , ReturnFlowPercent,ReturnFlowRate
         ! if ReturnFlowRate>PedalMeter, excess value(ReturnFlowRate-PedalMeter) is dumped in the code before
        
        
!!====================================================================== 
!!                           DRILL WATCH
!!======================================================================      
     
    data%EquipmentControl%DrillingWatch%PitGainLose= ((data%State%MudSystem%ActiveTankVolume/42.) - data%State%MudSystem%RefrencePitVolume_DrillWatch)    ! DrillWatch
    !write(*,*) 'PitGainLose galon' , PitGainLose*42.
    
    
    ! if (IsPortable) then
        
    !     MVT_MinVol_Allowded= data%EquipmentControl%DataDisplayConsole%PitAlarmLow
    !     MVT_MaxVol_Allowded= data%EquipmentControl%DataDisplayConsole%PitAlarmHigh 
 
    !      IF ( ActiveTankVolume/42. < (RefrencePitVolume-ABS(MVT_MinVol_Allowded)) .OR. ActiveTankVolume/42. > (RefrencePitVolume+ABS(MVT_MaxVol_Allowded)) ) THEN
             
    !          data%EquipmentControl%DataDisplayConsole%MVTAlarmLED = 1 !(blinking)
    !          IF (data%EquipmentControl%DataDisplayConsole%MVTHornSwitch) THEN
    !              data%EquipmentControl%DataDisplayConsole%Buzzer2= .TRUE.
    !          ELSE
    !              data%EquipmentControl%DataDisplayConsole%Buzzer2= .FALSE.
    !          ENDIF
             
    !      ELSE
    !          data%EquipmentControl%DataDisplayConsole%MVTAlarmLED = 0   !(OFF)
    !          data%EquipmentControl%DataDisplayConsole%Buzzer2= .false.
    !      ENDIF        

    ! endif
    

    if (data%State%StudentStation%PitGainLossZero) then
        
        data%EquipmentControl%DrillingWatch%PitGainLose= 0.d0 !DrillWatch
        data%State%MudSystem%RefrencePitVolume_DrillWatch= data%State%MudSystem%ActiveTankVolume/42.    !(bbl) !DrillWatch
        !*********************************************
        
        data%EquipmentControl%DataDisplayConsole%PitGainLossGauge= 0.    !MFF Indicator
        data%State%MudSystem%RefrencePitVolume= data%State%MudSystem%ActiveTankVolume/42.    !(bbl) !MFF Indicator

    endif
    
    
 
    
    
     
     
!!====================================================================== 
!!                           MUD FLOW-FILL INDICATOR
!!======================================================================        
        
     IF (data%EquipmentControl%DataDisplayConsole%MFFIPowerSwitch==1 ) THEN !.and. IsPortable==.false.          
         

!====================TotalStrokes Reset and Calculate======================         
        if (data%EquipmentControl%DataDisplayConsole%MFFIResetTotalStrokes == 1) then
              IF (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) THEN
                  data%State%MudSystem%TotalStrokes1MFFI =0.
              elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) THEN
                  data%State%MudSystem%TotalStrokes2MFFI =0.
              else
                  data%State%MudSystem%TotalStrokes1MFFI =0.
                  data%State%MudSystem%TotalStrokes2MFFI =0.
              endif
        endif
            data%State%MudSystem%TotalStrokes1MFFI= data%State%MudSystem%TotalStrokes1MFFI+((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline
            data%State%MudSystem%TotalStrokes2MFFI= data%State%MudSystem%TotalStrokes2MFFI+((data%EquipmentControl%DataDisplayConsole%MP2SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline
            
!==================FillStrokes Reset and Calculate=========================       
        if (data%EquipmentControl%DataDisplayConsole%MFFIResetFillCounter == 1) then
              IF (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) THEN
                  data%State%MudSystem%TotalFillStrokes1MFFI =0.
              elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) THEN
                  data%State%MudSystem%TotalFillStrokes2MFFI =0.
              else
                  data%State%MudSystem%TotalFillStrokes1MFFI =0.
                  data%State%MudSystem%TotalFillStrokes2MFFI =0.
              endif
        endif
         

            data%State%MudSystem%TotalFillStrokes1MFFI= data%State%MudSystem%TotalFillStrokes1MFFI+((data%EquipmentControl%DataDisplayConsole%MP1SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline
            data%State%MudSystem%TotalFillStrokes2MFFI= data%State%MudSystem%TotalFillStrokes2MFFI+((data%EquipmentControl%DataDisplayConsole%MP2SPMGauge)/60.)*data%State%MudSystem%DeltaT_Mudline
!=================================================================== 
            
            
            if (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) then
                data%EquipmentControl%DataDisplayConsole%MFFITotalStrokeCounter = real(nint(data%State%MudSystem%TotalStrokes1MFFI))      !TotalStroke LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) then
                data%EquipmentControl%DataDisplayConsole%MFFITotalStrokeCounter = real(nint(data%State%MudSystem%TotalStrokes2MFFI))      !TotalStroke LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 3) then
                data%EquipmentControl%DataDisplayConsole%MFFITotalStrokeCounter = real(nint(data%State%MudSystem%TotalStrokes1MFFI+data%State%MudSystem%TotalStrokes2MFFI))      !TotalStroke LED
            endif            
            
            
    IF (data%EquipmentControl%DataDisplayConsole%MFFIFillSPMSelectorSwitch== .false.) THEN    !(spm mode) 
            if (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = real(nint(data%EquipmentControl%DataDisplayConsole%MP1SPMGauge))     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = real(nint(data%EquipmentControl%DataDisplayConsole%MP2SPMGauge))     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 3) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter= real(nint(data%EquipmentControl%DataDisplayConsole%MP1SPMGauge+data%EquipmentControl%DataDisplayConsole%MP2SPMGauge))     !Fill or SPM LED
            endif  
            
    ELSE   ! (MFFIFillSPMSelectorSwitch== .true.) then    !(fill mode)
        if (data%State%MudSystem%ReturnFlowRate== 0) then
            if (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = real(nint(data%State%MudSystem%TotalFillStrokes1MFFI))     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = real(nint(data%State%MudSystem%TotalFillStrokes2MFFI))     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 3) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter= real(nint(data%State%MudSystem%TotalFillStrokes1MFFI+data%State%MudSystem%TotalFillStrokes2MFFI))     !Fill or SPM LED
            endif 
        

                data%State%MudSystem%TotalFilledStrokesBy1MFFI = real(nint(data%State%MudSystem%TotalFillStrokes1MFFI))! for values=fix on LED after the well filled
                data%State%MudSystem%TotalFilledStrokesBy2MFFI = real(nint(data%State%MudSystem%TotalFillStrokes2MFFI))! for values=fix on LED after the well filled
                data%State%MudSystem%TotalFilledStrokesBy1and2MFFI= real(nint(data%State%MudSystem%TotalFillStrokes1MFFI+data%State%MudSystem%TotalFillStrokes2MFFI))! for values=fix on LED after the well filled

            
            
        else !(ReturnFlowRate>0)
        
        ! these values=fix on LED after the well filled
            if (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 1) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = data%State%MudSystem%TotalFilledStrokesBy1MFFI     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 2) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter = data%State%MudSystem%TotalFilledStrokesBy2MFFI     !Fill or SPM LED
            elseif (data%EquipmentControl%DataDisplayConsole%MFFIPumpSelectorSwitch == 3) then
                data%EquipmentControl%DataDisplayConsole%FillStrokeCounter= data%State%MudSystem%TotalFilledStrokesBy1and2MFFI     !Fill or SPM LED
            endif 
        endif
    
        
    ENDIF
    

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

        

        
         if (data%State%MudSystem%ReturnFlowRate>0) then
             data%EquipmentControl%DataDisplayConsole%MFFIPumpLED=1      !(Returns Lamp)
         else
             data%EquipmentControl%DataDisplayConsole%MFFIPumpLED=0      !(Returns Lamp)
         endif
         

         
         IF (data%EquipmentControl%DataDisplayConsole%MFFISetAlarmSwitch==0) THEN
             
            data%EquipmentControl%DataDisplayConsole%ReturnMudFlowGauge= (1 - data%State%MudSystem%ReturnMudFlowGaugeMalf)*data%State%MudSystem%ReturnFlowPercent !(percent)    
         
         ELSEIF (data%EquipmentControl%DataDisplayConsole%MFFISetAlarmSwitch==-1) THEN
             data%State%MudSystem%MFFI_MinPercent_Allowded=data%EquipmentControl%DataDisplayConsole%MFFISetAlarmLowKnob
             data%EquipmentControl%DataDisplayConsole%ReturnMudFlowGauge= (1 - data%State%MudSystem%ReturnMudFlowGaugeMalf)*data%State%MudSystem%MFFI_MinPercent_Allowded
             
         ELSE   !(MFFISetAlarmSwitch==1)
             
             data%State%MudSystem%MFFI_MaxPercent_Allowded=data%EquipmentControl%DataDisplayConsole%MFFISetAlarmHighKnob
             data%EquipmentControl%DataDisplayConsole%ReturnMudFlowGauge= (1 - data%State%MudSystem%ReturnMudFlowGaugeMalf)*data%State%MudSystem%MFFI_MaxPercent_Allowded
         ENDIF         
         

         IF (data%State%MudSystem%ReturnFlowPercent<data%State%MudSystem%MFFI_MinPercent_Allowded .OR. data%State%MudSystem%ReturnFlowPercent>data%State%MudSystem%MFFI_MaxPercent_Allowded) THEN
             !write(*,*) 'alarm return:' , ReturnFlowRate
             data%EquipmentControl%DataDisplayConsole%MFFIAlarmLED = 2 !(blinking)
             IF (data%EquipmentControl%DataDisplayConsole%MFFIHornSwitch) THEN
             data%EquipmentControl%DataDisplayConsole%Buzzer3= .true.
             ELSE
                 data%EquipmentControl%DataDisplayConsole%Buzzer3= .FALSE.
             ENDIF
         ELSE
             data%EquipmentControl%DataDisplayConsole%MFFIAlarmLED = 0   !(OFF)
             data%EquipmentControl%DataDisplayConsole%Buzzer3= .false.
         ENDIF   
 !===================================================================================    
         
         
     ELSEIF (data%EquipmentControl%DataDisplayConsole%MFFIPowerSwitch==0) THEN
         data%EquipmentControl%DataDisplayConsole%ReturnMudFlowGauge= 0.
         data%EquipmentControl%DataDisplayConsole%FillStrokeCounter= 0
         data%EquipmentControl%DataDisplayConsole%MFFITotalStrokeCounter= 0
         data%EquipmentControl%DataDisplayConsole%MFFIAlarmLED= 0
         data%EquipmentControl%DataDisplayConsole%Buzzer3= .false.
     ENDIF
     
     
    ! if (  IsPortable ) then  

    !          MFFI_MinPercent_Allowded=data%EquipmentControl%DataDisplayConsole%RetFlowAlarmLow
    !          MFFI_MaxPercent_Allowded=data%EquipmentControl%DataDisplayConsole%RetFlowAlarmHigh
             
             
    !      IF (ReturnFlowPercent<MFFI_MinPercent_Allowded .OR. ReturnFlowPercent>MFFI_MaxPercent_Allowded) THEN
             
    !          data%EquipmentControl%DataDisplayConsole%MFFIAlarmLED = 1 !(blinking)
    !          IF (data%EquipmentControl%DataDisplayConsole%MFFIHornSwitch) THEN
    !          data%EquipmentControl%DataDisplayConsole%Buzzer3= .true.
    !          ELSE
    !              data%EquipmentControl%DataDisplayConsole%Buzzer3= .FALSE.
    !          ENDIF
    !      ELSE
    !          data%EquipmentControl%DataDisplayConsole%MFFIAlarmLED = 0   !(OFF)
    !          data%EquipmentControl%DataDisplayConsole%Buzzer3= .false.
    !      ENDIF               
             
    ! endif
    

!!====================================================================== 
!!              TRIP TANK PANEL DISPLAY VALUES
!!======================================================================    
     
            data%EquipmentControl%Tank%TripTankVolume = data%State%MudSystem%TripTankVolumeCalc/42.      !(Drill Watch display)
            data%EquipmentControl%Tank%TripTankDensity= data%State%MudSystem%TripTankDensityCalc      !(display) 

            
     IF (data%EquipmentControl%DataDisplayConsole%TripTankPowerSwitch==1  ) THEN !.and. IsPortable==.false.
     
         IF (data%EquipmentControl%DataDisplayConsole%TripTankSetAlarmSwitch==0) THEN
             
            data%EquipmentControl%DataDisplayConsole%TripTankGauge= (1 - data%State%MudSystem%TripTankPressure_DataDisplayMalf) * data%State%MudSystem%TripTankVolumeCalc      ! (gal)
         ELSEIF (data%EquipmentControl%DataDisplayConsole%TripTankSetAlarmSwitch==-1) THEN
             
             data%State%MudSystem%TripTank_MinVol_Allowded= data%EquipmentControl%DataDisplayConsole%TripTankSetAlarmLow/2.    ! 2: because knob input is 0-100 but gauge is 0-50
             data%EquipmentControl%DataDisplayConsole%TripTankGauge= (1 - data%State%MudSystem%TripTankPressure_DataDisplayMalf) * data%State%MudSystem%TripTank_MinVol_Allowded
             
         ELSE  !(TripTankSetAlarmSwitch==1) 
             data%State%MudSystem%TripTank_MaxVol_Allowded= data%EquipmentControl%DataDisplayConsole%TripTankSetAlarmHigh/2.    ! 2: because knob input is 0-100 but gauge is 0-50
             data%EquipmentControl%DataDisplayConsole%TripTankGauge= (1 - data%State%MudSystem%TripTankPressure_DataDisplayMalf) * data%State%MudSystem%TripTank_MaxVol_Allowded
         ENDIF     
         
         
         
          IF ((data%State%MudSystem%TripTankVolumeCalc < data%State%MudSystem%TripTank_MinVol_Allowded) .OR. (data%State%MudSystem%TripTankVolumeCalc > data%State%MudSystem%TripTank_MaxVol_Allowded)) THEN
             data%EquipmentControl%DataDisplayConsole%TripTankAlarmLED =  2 !(blinking)
             IF (data%EquipmentControl%DataDisplayConsole%TripTankHornSwitch) THEN
                 data%EquipmentControl%DataDisplayConsole%Buzzer1= .true.
             ELSE
                 data%EquipmentControl%DataDisplayConsole%Buzzer1= .false.     
            ENDIF
         ELSE
             data%EquipmentControl%DataDisplayConsole%TripTankAlarmLED =  0   !(OFF)
             data%EquipmentControl%DataDisplayConsole%Buzzer1= .false.
         ENDIF
         
        data%EquipmentControl%DataDisplayConsole%TripTankPumpLED=  data%EquipmentControl%DataDisplayConsole%TripTankPumpSwitch
         
            
     ELSEIF (data%EquipmentControl%DataDisplayConsole%TripTankPowerSwitch==0) THEN
         data%EquipmentControl%DataDisplayConsole%TripTankGauge= 0.  !(gal)
         data%EquipmentControl%DataDisplayConsole%TripTankAlarmLED= 0
         data%EquipmentControl%DataDisplayConsole%TripTankPumpLED= 0
         data%EquipmentControl%DataDisplayConsole%Buzzer1= .false. 
     ENDIF 
     
     
    ! if (  IsPortable ) then       
             
    !          TripTank_MinVol_Allowded= data%EquipmentControl%DataDisplayConsole%TripAlarmLow
    !          TripTank_MaxVol_Allowded= data%EquipmentControl%DataDisplayConsole%TripAlarmHigh
  

    !       IF ((TripTankVolumeCalc < TripTank_MinVol_Allowded) .OR. (TripTankVolumeCalc > TripTank_MaxVol_Allowded)) THEN
    !          data%EquipmentControl%DataDisplayConsole%TripTankAlarmLED =  1 !(blinking)
    !          IF (data%EquipmentControl%DataDisplayConsole%TripTankHornSwitch) THEN
    !              data%EquipmentControl%DataDisplayConsole%Buzzer1= .true.
    !          ELSE
    !              data%EquipmentControl%DataDisplayConsole%Buzzer1= .false.     
    !         ENDIF
    !      ELSE
    !          data%EquipmentControl%DataDisplayConsole%TripTankAlarmLED =  0   !(OFF)
    !          data%EquipmentControl%DataDisplayConsole%Buzzer1= .false.
    !      ENDIF 
         
    ! endif
    
                

                
        !write(*,*) '=====================================================================' 
  

        
        ! if (IsStopped) return
        
    end subroutine main
    

    
    
 !===================================================================================================================   
 !===================================================================================================================   
 !===================================================================================================================   
    
    subroutine ActiveMudVolumeChanged(v)
        !use CLog4
        implicit none
        real(8), intent (in) :: v
        !call Log_4('ActiveMudVolumeChanged=', v)
        data%State%MudSystem%ActiveTankVolume=  data%Configuration%Mud%ActiveMudVolumeGal       ! update from student input 
    end subroutine
    
    subroutine ActiveDensityChanged(v)
        !use CLog4
        implicit none
        real(8), intent (in) :: v
        !call Log_4('ActiveDensityChanged=', v)
        data%State%MudSystem%ActiveTankDensity=  data%Configuration%Mud%ActiveDensity       ! update from student input
    end subroutine
    
    subroutine ReserveMudVolumeChanged(v)
        !use CLog4
        implicit none
        real(8), intent (in) :: v
        !call Log_4('ReserveMudVolumeChanged=', v)
        data%State%MudSystem%ReserveTankVolume= data%Configuration%Mud%ReserveMudVolumeGal       ! update from student input
    end subroutine
    
    subroutine ReserveDensityChanged(v)
        !use CLog4
        implicit none
        real(8), intent (in) :: v
        !call Log_4('ReserveDensityChanged=', v)
        data%State%MudSystem%ReserveTankDensity= data%Configuration%Mud%ReserveDensity       ! update from student input 
    end subroutine
    
    ! subroutine SetupMudSystem()
    !     use CPathChangeEvents
    !     use CMudPropertiesVariables
    !     implicit none
        
    !     call BeforeTraverse%Add(InitialVarsBeforePathsChanges)
    !     call AfterTraverse%Add(AfterPathsChanges)
    !     call OnPathOpen%Add(WhenPathOpen)
        
        
    !     call OnActiveMudVolumeChange%Add(ActiveMudVolumeChanged)
    !     call OnActiveDensityChange%Add(ActiveDensityChanged)
    !     call OnReserveMudVolumeChange%Add(ReserveMudVolumeChanged)
    !     call OnReserveDensityChange%Add(ReserveDensityChanged)
        
    ! end subroutine
 
    subroutine AfterPathsChanges()
        implicit none
        integer i
        
        if(Pump1_Lasts%Length() <= 0) return
        do i = 1, Pump1_Lasts%Length()
            if(Pump2_Lasts%Length() <= 0) cycle
            if(any(Pump2_Lasts%Array == Pump1_Lasts%Array(i)))  then 
                State2 = .true.     ! Pumps 1 & 2 have same destination
                !print*, 'State2 = .true.'
            endif
            if(Pump3_Lasts%Length() <= 0) cycle
            if(any(Pump3_Lasts%Array == Pump1_Lasts%Array(i))) then
                State3 = .true.     ! Pumps 1 & 3 have same destination
                !print*, 'State3 = .true.'
            endif
        enddo
        
        if(Pump2_Lasts%Length() <= 0) return
        do i = 1, Pump2_Lasts%Length()
            if(Pump3_Lasts%Length() <= 0) cycle
            if(any(Pump3_Lasts%Array == Pump2_Lasts%Array(i))) then 
                State4 = .true.     ! Pumps 2 & 3 have same destination
                !print*, 'State4 = .true.'
            endif
        enddo
        
        State1 = State2 .and. State3     ! Pumps 1 & 2 & 3 have same destination
        !if(State1) print*, 'State1 = .true.'
        
    end subroutine
 
    subroutine InitialVarsBeforePathsChanges()
        implicit none
       
        condition1 = .false.
        condition2 = .false.
        condition3 = .false.
        condition4 = .false.
        condition5 = .false.
        condition6 = .false.
        condition7 = .false.
        condition8 = .false.
        condition9 = .false.
        condition10 = .false.
        condition11 = .false.
        condition12 = .false.
        condition13 = .false.
        condition14 = .false.
        condition15 = .false.
        condition16 = .false.
        condition17 = .false.
        condition18 = .false.
        condition19 = .false.
        condition20 = .false.
        condition21 = .false.
        condition22 = .false.
        condition23 = .false.
        condition24 = .false.
        condition25 = .false.
        condition26 = .false.
        condition27 = .false.
        condition28 = .false.
        condition29 = .false.
        condition30 = .false.
        condition31 = .false.
        condition32 = .true.
        condition33 = .true.
        condition34 = .true.
        condition35 = .false.
        condition36 = .false.
        condition37 = .false.
        condition38 = .false.
        condition39 = .false.
        condition40 = .false.
        condition41 = .false.
        condition42 = .false.
        condition43 = .false.
        condition44 = .false.
        condition45 = .false.
        condition46 = .false.
        condition47 = .false.
        condition48 = .false.
        condition49 = .false.
        condition50 = .false.
        condition51 = .false.
        condition52 = .false.
        condition53 = .false.
        condition54 = .false.
        condition55 = .false.
        condition56 = .false.
        condition57 = .false.
        condition58 = .false.
        condition59= .false.
        condition60= .false.
        condition61= .false.
        
        
        

        

        
        !ThereIsPathFrom82 = .false.
        !!print*, "ThereIsPathFrom82=",ThereIsPathFrom82
        !ThereIsPathFrom83 = .false.
        !!print*, "ThereIsPathFrom82=",ThereIsPathFrom82
        !ThereIsPathFrom84 = .false.
        !!print*, "ThereIsPathFrom82=",ThereIsPathFrom82
        
        ThereIsPathFrom_71_72_73_To_82 = .false.
        !print*, "ThereIsPathFrom_71_72_73_To_82=",ThereIsPathFrom_71_72_73_To_82
        ThereIsPathFrom_71_72_73_To_83 = .false.
        !print*, "ThereIsPathFrom_71_72_73_To_83=",ThereIsPathFrom_71_72_73_To_83
        ThereIsPathFrom_71_72_73_To_84 = .false.
        !print*, "ThereIsPathFrom_71_72_73_To_84=",ThereIsPathFrom_71_72_73_To_84
                
        DumpFromKelly_Pump1 = .false.
        DumpFromFillupHead_Pump1 = .false.
        DumpFromTopDrive_Pump1 = .false.
        
        
        DumpFromKelly_Pump2 = .false.
        DumpFromFillupHead_Pump2 = .false.
        DumpFromTopDrive_Pump2 = .false.
        
        
        DumpFromKelly_Pump3 = .false.
        DumpFromFillupHead_Pump3 = .false.
        DumpFromTopDrive_Pump3 = .false.
        
        
        
        State1 = .false.
        State2 = .false.
        State3 = .false.
        State4 = .false.
        
        call Pump1_Lasts%Empty()
        call Pump2_Lasts%Empty()
        call Pump3_Lasts%Empty()
        
        
        
        
        
        ac32 = .false.
        ac33 = .false.
        ac34 = .false.
        ac35 = .false.
        ac29 = .false.
        
    end subroutine
    
    subroutine WhenPathOpen(valves)
        use SimulationVariables
        implicit none
        integer, allocatable, intent (in) :: valves(:)
        integer :: first, last
        if (.not.allocated(valves)) return
        if(size(valves) <= 0) return 
        
        if ( any(valves == 32)) ac32 = .true.
        if ( any(valves == 33)) ac33 = .true.
        if ( any(valves == 34)) ac34 = .true.
        if ( any(valves == 35)) ac35 = .true.
        if ( any(valves == 29)) ac29 = .true.
        
        
        first = 1
        last = size(valves)
        
        MP1_Q = data%State%Pump(1)%Flow_Rate
        MP2_Q = data%State%Pump(2)%Flow_Rate
        MP3_Q = data%State%Pump(3)%Flow_Rate
        
        
        
        if(valves(first) == 82) call Pump1_Lasts%Add(valves(last))
        if(valves(first) == 83) call Pump2_Lasts%Add(valves(last))
        if(valves(first) == 84) call Pump3_Lasts%Add(valves(last))
        
        !print*, '=============================================='
        !do i = 1, Pump1_Lasts%Length()
        !    print*, 'mp1=', Pump1_Lasts%Array(i)
        !enddo
        !
        !print*, '-------------------------------'
        !
        !do i = 1, Pump2_Lasts%Length()
        !    print*, 'mp2=', Pump2_Lasts%Array(i)
        !enddo
        !
        !print*, '-------------------------------'
        !
        !
        !do i = 1, Pump3_Lasts%Length()
        !    print*, 'mp3=', Pump3_Lasts%Array(i)
        !enddo
        !
        !print*, '=============================================='
        
        
        !if(valves(first)==82 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71)) then
        !    ThereIsPathFrom82 = .true.
        !    !print*, "ThereIsPathFrom82=",ThereIsPathFrom82
        !endif
        !
        !if(valves(first)==83 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71)) then
        !    ThereIsPathFrom83 = .true.
        !    !print*, "ThereIsPathFrom83=",ThereIsPathFrom83
        !endif
        !
        !if(valves(first)==84 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71)) then
        !    ThereIsPathFrom84 = .true.
        !    !print*, "ThereIsPathFrom84=",ThereIsPathFrom84
        !endif
        
        if(valves(last)==82 .and. (valves(first)==71 .or. valves(first)==72 .or. valves(first)==73)) then
            ThereIsPathFrom_71_72_73_To_82 = .true.
            !print*, "ThereIsPathFrom_71_72_73_To_82=",ThereIsPathFrom_71_72_73_To_82
        endif
        
        if(valves(last)==83 .and. (valves(first)==71 .or. valves(first)==72 .or. valves(first)==73)) then
            ThereIsPathFrom_71_72_73_To_83 = .true.
            !print*, "ThereIsPathFrom_71_72_73_To_83=",ThereIsPathFrom_71_72_73_To_83
        endif
        
        if(valves(last)==84 .and. (valves(first)==71 .or. valves(first)==72 .or. valves(first)==73)) then
            ThereIsPathFrom_71_72_73_To_84 = .true.
            !print*, "ThereIsPathFrom_71_72_73_To_84=",ThereIsPathFrom_71_72_73_To_84
        endif
                
        !if (.not.allocated(OpenPaths)) exit
                !===============TanksToMudPump1===================
                if(valves(last)==82)    then
                    if(valves(first)==71) then
                        !j2=j2+1
                        !A71=1
                        condition1 = .true.
                    endif
                    
                    if(valves(first)==72) then
                        !j2=j2+1
                        !A72=1
                        condition2 = .true.
                    endif
                    
                    if(valves(first)==73) then
                        !j2=j2+1
                        !A73=1
                        condition3 = .true.
                    endif
                    
                endif
                !================================================
                 
                
                !============BellNippleToPits-FullWell(MLnumber=3)==============

                if ( Manifold%Valve(41)%Status == .false. .and. Manifold%Valve(42)%Status == .false. )   then
                    call ChangeValve(60, .TRUE.)
                else
                    call ChangeValve(60, .FALSE.)
                endif
                
                if(valves(first)==80 .and. valves(last)==71 .and. any(valves == 42)) condition4 = .true.
                if(valves(first)==80 .and. valves(last)==77 .and. any(valves == 41)) condition5 = .true.
                if(valves(first)==80 .and. valves(last)==78) condition6 = .true.

                !================================================
            
                
                !============WellToChokeManifold(Through 26)==============          
                if(valves(first)==79 .and. any(valves == 26)) then
                    if(valves(last)==71) then
                        !j4=j4+1
                        !C71=1.
                        condition7 = .true.
                    endif
                    
                    if(valves(last)==77) then
                        !j4=j4+1
                        !C77=1.
                        condition8 = .true.
                    endif
                    
                    if(valves(last)==78) then
                        !j4=j4+1
                        !C78=1.
                        condition45 = .true.
                    endif                                       
                    
                endif 

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

                
                !============ActiveTankToTripTank==============          
                if(valves(first)==71 .and. valves(last)==77) then
                        !j5=j5+1
                        condition9 = .true.
                endif
                !================================================            
                
                    
                    
                !============TripTankToActiveTank And BellNipple==============          
                if(valves(first)==77) then
                    if(valves(last)==71) then
                        !j6=j6+1
                        !D71=1
                        condition10 = .true.
                    endif
                    
                    if(valves(last)==80) then
                        !j6=j6+1
                        !D80=1
                        condition11 = .true.
                    endif
                    
                endif
                !================================================                    
        
                    
                !============ActiveTankToDump==============          
                if(valves(first)==71 .and. valves(last)==78) then
                    !j7=j7+1
                    condition12 = .true.                 
                endif
                !================================================                      
                    
                
                !============TripTankToDump==============          
                if(valves(first)==77 .and. valves(last)==78) then
                    !j8=j8+1
                    condition13 = .true.                 
                endif
                !================================================ 
                
                
                !============WellToBellNipple==============          
                if(valves(first)==79 .and. valves(last)==80) then
                    !j9=j9+1
                    condition14 = .true.                 
                endif
                !================================================                  
                
                !============MudBucketToBellNipple==============          
                if(valves(first)==81 .and. valves(last)==80) then
                    !j10=j10+1
                    condition15 = .true.                 
                endif
                !================================================  
                
              
                !============BellNippleToWell-NonFullWell==============
                if(valves(first)==80 .and. valves(last)==79) then    ! Well is NOT Full
                    !j11=j11+1
                    condition16 = .true.
                endif                
                !================================================                
                
                !===============TanksToMudPump2===================
                if(valves(last)==83)    then
                    if(valves(first)==71) then
                        !j12=j12+1
                        !E71=1
                        condition17 = .true.
                    endif
                    
                    if(valves(first)==72) then
                        !j12=j12+1
                        !E72=1
                        condition18 = .true.
                    endif
                    
                    if(valves(first)==73) then
                        !j12=j12+1
                        !E73=1
                        condition19 = .true.
                    endif
                    
                endif
                !================================================                 
      
                
                !===============TanksToCementPump===================
                if(valves(last)==84)    then
                    if(valves(first)==71) then
                        !j13=j13+1
                        !F71=1
                        condition20 = .true.
                    endif
                    
                    if(valves(first)==72) then
                        !j13=j13+1
                        !F72=1
                        condition21 = .true.
                    endif
                    
                    if(valves(first)==73) then
                        !j13=j13+1
                        !F73=1
                        condition22 = .true.
                    endif
                    
                endif
                !================================================                   
                
                !===============PumpsToString===================
                if(valves(last)==79)    then
                    if(valves(first)==82) then
                        !j14=j14+1
                        !G82=1
                        condition23 = .true.
                    endif
                    
                    if(valves(first)==83) then
                        !j14=j14+1
                        !G83=1
                        condition24 = .true.
                    endif
                    
                    if(valves(first)==84) then
                        !j14=j14+1
                        !G84=1
                        condition25 = .true.
                    endif
                    
                endif
                !================================================ 
                
                
     
                
                
                !============MudPump1HasPath===================          
                if(ThereIsPathFrom_71_72_73_To_82 .and. (valves(first)==82 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71))) then
                    !Mp1_NoPath= 0
                    condition32 = .false. 
                endif
                data%State%MudSystem%condition32Final = condition32 
                !================================================                

                
                !============MudPump2HasPath===================          
                if(ThereIsPathFrom_71_72_73_To_83 .and. (valves(first)==83 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71))) then
                    !write(*,*) 'condition33 ******'
                    !Mp2_NoPath= 0
                    condition33 = .false.                
                endif
                data%State%MudSystem%condition33Final= condition33
                !================================================   
                             
                
                !============CementPumpHasNoPath===================          
                if(ThereIsPathFrom_71_72_73_To_84 .and. (valves(first)==84 .and. (valves(last)==79 .or. valves(last)==78 .or. valves(last)==77 .or. valves(last)==71))) then
                    !Cp_NoPath= 1
                    condition34 = .false.                 
                endif
                data%State%MudSystem%condition34Final = condition34                 
                !================================================                
 
                
                
                
                !===============PumpsToDump===================
                !DumpFromKelly = 0.0
                !DumpFromFillupHead= 0.0
                
                if(valves(last)==78)    then
                    if(valves(first)==82) then
                        !DumpPump1=1
                        condition26 = .true.
                        IF(any(valves == 56)) DumpFromKelly_Pump1 = .true.
                        IF(any(valves == 14)) DumpFromFillupHead_Pump1 = .true.
                        IF(any(valves == 70)) DumpFromTopDrive_Pump1 = .true.
                        

                    endif
                    
                    
                    if(valves(first)==83) then
                        !DumpPump2=1
                        print*, "THERE IS DUMP"
                        condition27 = .true.
                        IF(any(valves == 56)) DumpFromKelly_Pump2 = .true.
                        IF(any(valves == 14)) DumpFromFillupHead_Pump2 = .true.
                        IF(any(valves == 70)) DumpFromTopDrive_Pump2 = .true.

                    endif
                    
                    
                    if(valves(first)==84) then
                        !DumpCementPump=1
                        condition28 = .true.
                        IF(any(valves == 56)) DumpFromKelly_Pump3 = .true.
                        IF(any(valves == 14)) DumpFromFillupHead_Pump3 = .true.
                        IF(any(valves == 70)) DumpFromTopDrive_Pump3 = .true.
 
                    endif
                    
                    ! DumpFromKelly
                    !if (DumpFromKelly_Pump1 .or. DumpFromKelly_Pump2 .or. DumpFromKelly_Pump3) then
                    !    DumpFromKelly = 1.0
                    !else
                    !    DumpFromKelly = 0.0
                    !endif
                    
                    
                    ! DumpFromFillupHead
                    if (DumpFromFillupHead_Pump1 .or. DumpFromFillupHead_Pump2 .or. DumpFromFillupHead_Pump3) then
                        DumpFromFillupHead = 1.0
                    else
                        DumpFromFillupHead = 0.0
                    endif
                    
                endif
                
                
                
                !================================================                 
                
                
                !=======MudPumps1&2ToActiveTank_Through65&66==========
                
                ! << if H82 or H83 or H4 are open, no flow goes to other parts of system >>                
 
                
                if(valves(last)==71)    then
                    if(valves(first)==82 .and. any(valves == 65)) then
                        !j15=j15+1
                        !H82=1.0
                        condition29 = .true.
                    endif
                    
                    if(valves(first)==83 .and. any(valves == 66)) then
                        !j15=j15+1
                        !H83=1.0
                        condition30 = .true.
                    endif
                    
                endif
                !================================================                 
                
                !=======CementPumpToCementTank_Through67==========
                
                ! << if H82 or H83 or H4 are open, no flow goes to other parts of system >>                
                
                
                if(valves(last)==73 .and. valves(first)==84 .and. any(valves == 67))    then
                    
                    !H84=1.0
                    condition31 = .true.
                    
                endif
                !================================================  
                
                
   
                !===============PathsToGauge75===================
                if(valves(last)==75)    then
                    if(valves(first)==82) then      !Pump1 to Gauge75
                        !j16=j16+1
                        !K82=1
                        condition35 = .true.
                    endif
                    
                    if(valves(first)==83) then      !Pump2 to Gauge75
                        !j16=j16+1
                        !K83=1
                        condition36 = .true.
                    endif
                    
                    if(valves(first)==84) then      !Pump3 to Gauge75
                        !j16=j16+1
                        !K84=1
                        condition37 = .true.
                    endif
                    
                    if(valves(first)==79) then      !String to Gauge75
                        !j16=j16+1
                        !K79=1
                        condition38 = .true.
                    endif
                    
                    if(valves(first)==78) then      !Dump to Gauge75
                        !j16=j16+1
                        !K78=1
                        condition39 = .true.
                    endif                       
                    
                endif
                !================================================ 
                
                !===============PathsToGauge76===================
                if(valves(last)==76)    then
                    if(valves(first)==82) then      !Pump1 to Gauge76
                        !j17=j17+1
                        !L82=1
                        condition40 = .true.
                    endif
                    
                    if(valves(first)==83) then      !Pump2 to Gauge76
                        !j17=j17+1
                        !L83=1
                        condition41 = .true.
                    endif
                    
                    if(valves(first)==84) then      !Pump3 to Gauge76
                        !j17=j17+1
                        !L84=1
                        condition42 = .true.
                    endif
                    
                    if(valves(first)==79) then      !String to Gauge76
                        !j17=j17+1
                        !L79=1
                        condition43 = .true.
                    endif
                    
                    if(valves(first)==78) then      !Dump to Gauge76
                        !j17=j17+1
                        !L78=1
                        condition44 = .true.
                    endif                     
            
                endif
                !================================================                 
                           
                
                !====Pump1-StandPipeManifoldToChokeManifold-Through ChokeLine====          
                if(valves(first)==82 .and. any(valves == 2)) then
                    if(valves(last)==71) then
                        !j18=j18+1
                        !M71=1.
                        !Pump1toCh= 1.
                        condition46 = .true.
                    endif
                    
                    if(valves(last)==77) then
                        !j18=j18+1
                        !M77=1.
                        !Pump1toCh= 1.
                        condition47 = .true.
                    endif
                    
                    if(valves(last)==78) then
                        !j18=j18+1
                        !M78=1.
                        !Pump1toCh= 1.
                        condition48 = .true.
                    endif                                       
                    
                endif                 
                !=================================================================                 
                
                
                !====Pump2-StandPipeManifoldToChokeManifold-Through ChokeLine====          
                if(valves(first)==83 .and. any(valves == 2)) then
                    if(valves(last)==71) then
                        !j18=j18+1
                        !M71=1.
                        !Pump2toCh= 1.
                        condition49 = .true.
                    endif
                    
                    if(valves(last)==77) then
                        !j18=j18+1
                        !M77=1.
                        !Pump2toCh= 1.
                        condition50 = .true.
                    endif
                    
                    if(valves(last)==78) then
                        !j18=j18+1
                        !M78=1.
                        !Pump2toCh= 1.
                        condition51 = .true.
                    endif                                       
                    
                endif                 
                !=================================================================                 
                
                
                !====Pump3-StandPipeManifoldToChokeManifold-Through ChokeLine====          
                if(valves(first)==84 .and. any(valves == 2)) then
                    if(valves(last)==71) then
                        !j18=j18+1
                        !M71=1.
                        !Pump3toCh= 1.
                        condition52 = .true.
                    endif
                    
                    if(valves(last)==77) then
                        !j18=j18+1
                        !M77=1.
                        !Pump3toCh= 1.
                        condition53 = .true.
                    endif
                    
                    if(valves(last)==78) then
                        !j18=j18+1
                        !M78=1.
                        !Pump3toCh= 1.
                        condition54 = .true.
                    endif                                       
                    
                endif                 
                !================================================================= 
                


                
                !===============PumpsToWell_KillLine============
                if(valves(last)==79)    then
                    if(valves(first)==82) then
                        !j19=j19+1
                        !N82=1
                        condition55 = .true.
                    endif
                    
                    if(valves(first)==83) then
                        !j19=j19+1
                        !N83=1
                        condition56 = .true.
                    endif
                    
                    if(valves(first)==84) then
                        !j19=j19+1
                        !N84=1
                        condition57 = .true.
                    endif
                    
                endif
                !================================================                
                
                !===============WellToChokeLineGauge============
                if(valves(first)==79 .and. valves(last)==85)    then
                        !j20=j20+1
                        condition58 = .true.
                endif
                !================================================                  
                
                
                !============ChokeLineGaugeToTanks===============          
                if(valves(first)==85) then
                    if(valves(last)==71) then
                        !j21=j21+1
                        condition59 = .true.
                    endif
                    
                    if(valves(last)==77) then
                        !j21=j21+1
                        condition60 = .true.
                    endif
                    
                    if(valves(last)==78) then
                        !j21=j21+1
                        condition61 = .true.
                    endif                                       
                    
                endif                 
                !================================================            
                        
    end subroutine  
    
end module MudSystemModule