MODULE MudSystemVARIABLES

    use DynamicDoubleArray, only:DynamicDoubleArrayType
    use DynamicIntegerArray, only:DynamicIntegerArrayType
    use CDownHoleVariables
    
! use CBopControlPanel
! use CEquipmentsConstants
! use CAccumulatorVariables
! use CBopStackVariables
! use CChokeControlPanelVariables
! use CStandPipeManifoldVariables
! USE CReservoirVariables


IMPLICIT NONE

    integer, parameter :: BlownThreshold = 10
    !specific gravity of liquid
    !water density(kg/m^3)
    PARAMETER PII=3.14159265
    
    integer imud

    type::MudSystemType
        ! temporary varibales for solving pressure jerks -- 1399-11-09 
        integer Pump1BlownCount, Pump2BlownCount, Pump3BlownCount

        !integer Pump1BlownInTimeStep, Pump2BlownInTimeStep, Pump3BlownInTimeStep
        !logical Pump1BlownStarted, Pump2BlownStarted, Pump3BlownStarted
        !integer, parameter :: BlownThresholdInSecond = 5

        real(8) total_add,total_injected
        real(8) DeltaWellCap,WellCapOld,AnnCapOld,DeltaAnnCap

        !========================================================================
        !                               KICK VARIABLES
        !========================================================================
        REAL(8) KickDeltaVinAnnulus, KickVolumeinAnnulus
        REAL(8) Kick_Forehead_X,Kick_RemainedVolume_in_LastSection,BackheadX,KickDv,KickDx,MinKickDv,Old_KickBackHead_X,Kick_Density 
        INTEGER NewInfluxElementCreated,Kick_Forehead_section,MudSection,Op_KickLoc,Ann_KickLoc,FirstSetKickMigration,Old_KickBackHead_Section
        Integer iLoc,ChokeLine_KickLoc,KickNumber,NewInfluxNumber,SoundGasThroughChoke

        LOGICAL DrillingMode
        !real(8) HZ_ADD
        integer Flow_timeCounter,MudSys_timeCounter,FluidFlowCounter
        !========================================================================
        !                               MUD CIRCULATION
        !========================================================================
        REAL(8), ALLOCATABLE:: Xstart_PipeSection(:),Xend_PipeSection(:),PipeSection_VolumeCapacity(:),Area_PipeSectionFt(:),OD_PipeSectionInch(:),ID_PipeSectionInch(:),Angle_PipeSection(:)
        REAL(8), ALLOCATABLE:: Xstart_OpSection(:),Xend_OpSection(:),Area_OpSectionFt(:),OD_OpSectionInch(:),ID_OpSectionInch(:),OpSection_VolumeCapacity(:),GeoTypeOp(:),Angle_OpSection(:)
        REAL(8), ALLOCATABLE:: TDXstart_MudElementArray(:) , TDXend_MudElementArray(:) , TDDensity_MudElementArray(:)

        INTEGER, ALLOCATABLE:: GeoType(:)
        real(8) StMudVolumeSum,St_MudSaved_Density,St_Saved_MudDischarged_Volume,St_Saved_MudDischarged_Volume_Final,MudVolume_InjectedToBH,MudVolume_InjectedFromAnn
        real BitMudDensity
        REAL(8) xx,NewVolume,UtubeEmptyVolume,NewDensity, MudCircVerticalDepth,TrueMinValue

        REAL DirectionCoef
        INTEGER isection,OpSection,SuctionMud,NoStringMudElements,ImudCount,NoCasingMudElements,NoHorizontalMudElements,AddedElementsToString
        Integer TDNoHorizontalMudElements, TDNoStringMudElements, TDNoCasingMudElements
        Integer istring,icasing,NoPipeSections,FirstMudSet
        INTEGER NoBottomHoleMudElements,NoStringMudElementsForPlot,F_StringIntervalCounts_Old
        INTEGER FirstSetUtube1,FirstSetUtube2,FirstAdded,NewPipeFilling,Hz_MudOrKick_Utube,UtubeFilling,totalLength
        REAL(8) DeltaVolumeOp,DeltaVTemp,OldPosition,StringFlowRate,StringFlowRateFinal,AnnulusFlowRateFinal,TD_RemoveVolume_Remained,DeltaVolumePipe,DeltaVolumeAnnulusCapacity
        REAL AnnulusFlowRate,ChokeLineFlowRate
        Logical:: UtubePossibility,MudIsChanged,AddedPipe,UtubeMode1Activated,UtubeMode2Activated,WellisNOTFull,ChokeLineNOTFull
        Logical:: ShoeLost,ShoeFractured,Kickexpansion_DueToMudLost,LostInTripOutIsDone
        Integer  UGBOSuccessionCounter, UGBOSuccessionCounterOld
        REAL(8) Area_ChokeLineFt, ChokeLine_VolumeCapacity,TotalAddedVolume,LackageMudVolumeAfterFilling, LackageMudVolume, NewInflux_Density
        real(8)  DensityMixTol,Hz_Density_Utube,CuttingDensityMixTol,Op_Kick_Saved_Volume,Op_MudSaved_Density,Op_KickSaved_Density,Op_Saved_MudDischarged_Volume,OpMudVolumeSum,Op_NeededVolume_ToFill
        real(8) Choke_Kick_Saved_Volume,Choke_Saved_MudDischarged_Volume,Choke_KickSaved_Density,Choke_MudSaved_Density,ChokeMudVolumeSum
        integer Saved_Op_MudOrKick,Saved_Ann_MudOrKick,Saved_Choke_MudOrKick
        real(8) Choke_Saved_MudDischarged_Volume_Final,Choke_Kick_Saved_Volume_Final
        real(8) Qlost,FormationLostPressure,ShoeMudPressure,ShoeLostCoef, ShoeMudViscosity, ShoeMudDensity ,OldAnnulusCapacity
        logical:: Ann_to_Choke_2mud
        real(8) AnnMudVolumeSum,Ann_MudSaved_Density,Ann_KickSaved_Density,Ann_Saved_MudDischarged_Volume,Ann_Kick_Saved_Volume,Ann_Saved_MudDischarged_Volume_Final, Ann_Kick_Saved_Volume_Final
        type(DynamicDoubleArrayType) :: Hz_MudDischarged_Volume,Hz_Mud_Backhead_X,Hz_Mud_Forehead_X,Hz_Density,Hz_RemainedVolume_in_LastSection,Hz_EmptyVolume_inBackheadLocation, &
                                        Op_MudDischarged_Volume,Op_Mud_Backhead_X,Op_Mud_Forehead_X,Op_Density,Op_RemainedVolume_in_LastSection,Op_EmptyVolume_inBackheadLocation

        type(DynamicDoubleArrayType) :: ChokeLine_MudDischarged_Volume,ChokeLine_Mud_Backhead_X,ChokeLine_Mud_Forehead_X,ChokeLine_Density,ChokeLine_RemainedVolume_in_LastSection, &
                                        ChokeLine_EmptyVolume_inBackheadLocation


        type(DynamicDoubleArrayType) :: St_MudDischarged_Volume,St_Mud_Backhead_X,St_Mud_Forehead_X,St_Density,St_RemainedVolume_in_LastSection, &
                                    St_EmptyVolume_inBackheadLocation,Ann_MudDischarged_Volume,Ann_Mud_Backhead_X,Ann_Mud_Forehead_X, &
                                    Ann_Density,Ann_RemainedVolume_in_LastSection,Ann_EmptyVolume_inBackheadLocation
            
        type(DynamicIntegerArrayType) :: St_Mud_Backhead_section,St_Mud_Forehead_section,Ann_Mud_Backhead_section,Ann_Mud_Forehead_section,MudGeoType,Hz_Mud_Backhead_section,Hz_Mud_Forehead_section, &
                                        Op_Mud_Backhead_section,Op_Mud_Forehead_section,Hz_MudOrKick,St_MudOrKick,Ann_MudOrKick,Op_MudOrKick,ChokeLine_MudOrKick,MudTypeOp_MudElement,MudType_MudElement

        type(DynamicIntegerArrayType) :: ChokeLine_Mud_Backhead_section,ChokeLine_Mud_Forehead_section,Ann_CuttingMud

        type(DynamicDoubleArrayType) :: Xend_MudElement,Xstart_MudElement,Density_MudElement,PipeID_MudElement,PipeOD_MudElement,Angle_MudElement,  &
                                    Xstart_OpMudElement,Xend_OpMudElement,Density_OpMudElement,PipeID_OpMudElement,PipeOD_OpMudElement!,Angle_OpMudElement 
            
        type(DynamicDoubleArrayType) ::  TVDstart_MudElement, TVDend_MudElement, TVDstart_OpMudElement, TVDend_OpMudElement
        
        
        type(CFluid), allocatable :: StringMudElement(:), CasingMudElement(:)


            real(8) PressureGauge75,PressureGauge76

        !========================================================================
        !                           MALFUNCTION VARIABLES
        !========================================================================
        INTEGER StandPipeGauge1Malf, StandPipeGauge2Malf, StandPipePressure_DataDisplayMalf,StandPipePressureChokeMalf,DrillPipePressureMalf
        integer TripTankPressure_DataDisplayMalf,PitGainLossGaugeMalf,ReturnMudFlowGaugeMalf,MudTanksVolumeGaugeMalf

        !========================================================================
        !                           TRIP TANK VARIABLES
        !========================================================================
        logical condition32Final,condition33Final,condition34Final
        REAL(8) TripTank_Vol,TripTank_Dens,ReturnToTrip_Q,ActiveToTrip_Q,TripTankPump_Q,ReturnToTrip_Dens,ActiveToTrip_Dens,ReturnToTrip_deltaV,ActiveToTrip_deltaV
        REAL(8) MassFlowRate_ReturnToTrip,MassFlowRate_ActiveToTrip,TripTankPump_deltaV,MassFlowRate_TripTankPump,NetMassFlux_tripTank
        REAL(8) TripTank_MinVol_Allowded,TripTank_MaxVol_Allowded

        !!====================================================================== 
        !!                           MUD VOLUME TOTALIZER
        !!======================================================================
        REAL(8) RefrencePitVolume_DrillWatch        ! for DrillWatch
        REAL(8) MudTank1_vol,MudTank2_vol,MudTank3_vol,MudTank4_vol
        REAL(8) MVT_MinVol_Allowded,MVT_MaxVol_Allowded,MudTanksVolume
        REAL(8) PitGainLossZero,MVTCoarse,MVTFine,RefrencePitVolume,PitGainLossZero_Old,MVTCoarseKnob_Old,MVTFineKnob_Old
        REAL(8) ActiveTankDensity,TripTankDensityCalc,SuctionDensity_Old,AnnulusSuctionDensity_Old,StringDensity_Old,ChokeLineDensity_Old,ChokeManifoldDumpVolume
        LOGICAL FirstSet_Time

        !!====================================================================== 
        !!                           MUD FLOW-FILL INDICATOR
        !!====================================================================== 
        REAL(8) TotalStrokes1MFFI,TotalStrokes2MFFI,TotalStrokesPump1,TotalStrokesPump2,GraphTotalStrokes
        REAL(8) PedalMeter,ReturnFlowRate,ReturnFlowPercent,MFFI_MinPercent_Allowded,MFFI_MaxPercent_Allowded
        REAL(8) TotalFillStrokes1MFFI,TotalFillStrokes2MFFI,TotalFilledStrokesBy1MFFI,TotalFilledStrokesBy2MFFI,TotalFilledStrokesBy1and2MFFI

        !============================================================================
        !                       	MUD & ENVIRONMENT VARIABLES
        !============================================================================
        INTEGER NO_MudMinors,NO_PIPINGSMUDLINE
        REAL(8) Pumps_Height,String_Height,STpipeGauge_Height,Pits_Height,ChokeManifold_Height,WellChokeExit_Height
        REAL(8) STGauge_Pressure,String_Input_Pressure,Well_Output_Pressure,Pressure_BeforeChokes,Pressure_AfterChokes
        REAL(8) OpenArea32,OpenArea33,OpenArea34,OpenArea35,deltaPchoke,WellOutletDensity,ChokeOutletDensity
        REAL Q_flow32,Q_flow33,Q_flow34,Q_flow35
        REAL(8) DeltaT_Mudline,ActiveTankVolume,ReserveTankVolume,CementTankVolumeCalc,ActiveTankSettled,ActiveTankFloorArea,TripTankFloorArea
        REAL(8) TripTankVolumeCalc,BellNippleDensity,BellNippleVolume,MudBucketDensity,MudBucketVolume,BellNippleDumpVolume
        REAL(8) ReserveTankDensity,CementTankDensityCalc,Mp1Density,Mp2Density,Mp3Density,PumpsDumpVolume
        real PumpsDumpFlowRate
        REAL(8) Density_Ch
        real(8) Suction_Density_MudSystem,Suction_Density_PumpsToWell,CompressedMudDensity
        Logical WellToPitsOpen,WellToChokeManifoldOpen,MudChecked,WellHeadIsOpen
        logical Pump1OffFailure,Pump2OffFailure,Pump3OffFailure,ChokeLineGaugeToTanks,WellToChokeLineGauge
        REAL,ALLOCATABLE:: MudMinors(:,:),AREA_MUDLINE(:),MINORDIAMETER_MUDLINE(:),NOTE_MUDLINE(:),AREAMINOR_MUDLINE(:),LF_MUDLINE(:),CV_MUDLINE(:)
        REAL,ALLOCATABLE:: DIAM_MUDLINE_INCH(:),LENGT_MUDLINE(:),ROUGHNESS_MUDLINE(:),RELROUGH_MUDLINE(:),PIPINGS_MUDLINE(:,:)
    end type MudSystemType
    
    TYPE, PUBLIC :: MUD_TypeVars
        REAL Q,nu,Mud_Density,Mud_SG
        REAL minlosspa_MUDLINE,minloss_MUDLINE     ! MINORS 
        REAL Re_MUDline,fric,fricloss,static_loss,total_loss     ! MUDLINE 
    END TYPE MUD_TypeVars
    
    !data%State%MUD(1)%Q : -------------
    !data%State%MUD(2)%Q : PumpsToString
    !data%State%MUD(3)%Q : BellNippleToPits-FullWell
    !data%State%MUD(4)%Q : WellToChokeManifold
    !data%State%MUD(5)%Q : ActiveTankToTripTank
    !data%State%MUD(6)%Q : TripTankToActiveTank
    !data%State%MUD(7)%Q : WellToBellNipple
    !data%State%MUD(8)%Q : BellNippleToWell-NonFullWell
    !data%State%MUD(9)%Q : StandPipeManifoldToChokeManifold-Through ChokeLine
    !data%State%MUD(10)%Q : PumpsToWell_KillLine   
 
    ! TYPE, PUBLIC :: MUD_TypeVars2D
    ! !! MINORS    
    ! !REAL,ALLOCATABLE:: minlosspa_MUDLINE(:,:),minloss_MUDLINE(:,:)
    ! !! MUDLINE  
    ! !REAL,ALLOCATABLE:: Re_MUDline(:,:),fric(:,:),fricloss(:,:)
    ! END TYPE MUD_TypeVars2D
    
    ! TYPE(MUD_TypeVars2D) :: MUDS    

END MODULE