load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/shea_util.ncl"

begin
N = 384
r = 64
N = N/r
N = N*N
print("N = "+N)

f = addfile("data/third0.nc","r")
th = f->third0
f = addfile("data/J.nc","r")
J = f->J

nd = dimsizes(th)
third = new((/nd(0),nd(1),nd(2)/),float)
do i = 0,159
    if(ismissing(J(i)).eq.True) then
        third(i,:,:) = third@_FillValue
    end if
    if(ismissing(J(i)).eq.False) then
        if(J(i).ne.0) then
            do i1 = 0,nd(1)-1
                do i2 = 0,nd(2)-1
                    third(i,i1,i2) = (N-J(i))*th(i,i1,i2)/J(i)
                end do
            end do
        else
            third(i,:,:) = 0.
        end if
    end if
end do
third!0 = "time"
third!1 = "y"
third!2 = "x"
printVarSummary(third)
printMinMax(third,True)

fn = "data/third.nc"
system("rm -f "+fn)
filout = addfile(fn,"c")
filout->third = third
end
