Apologies fore the long post that would follow, but I am having error estimating cluster robust 3SLS GMM estimator using Moptimize. The following is the code below:

mata
N = rows(y1)
//y
y = y1\y2\y3
//x
x=blockdiag(x1, blockdiag(x2,x3))
//z
z=blockdiag(z1, blockdiag(z2,z3))
sel11 = J(N,1,1)
sel12 = J(N,1,0)
sel13 = J(N,1,0)
sel1=(sel11\sel12\sel13)
sel2=(sel12\sel11\sel13)
sel3=(sel12\sel13\sel11)

id = st_data(. , ("_ID"))
info = panelsetup(id,1)
nc = rows(info)
b0 = J(1, cols(x), 0)
D = J(cols(z), cols(z), 0 )

function oiv_gmm( M, todo, b, q, S, H) {
real scalar nc
y = moptimize_util_depvar(M,1)
xb = moptimize_util_xb(M,b,1)
z1 = moptimize_util_userinfo(M, 1)
z2 = moptimize_util_userinfo(M, 2)
z3 = moptimize_util_userinfo(M, 3)
z = moptimize_util_userinfo(M, 4)
sel1 = moptimize_util_userinfo(M, 5)
sel2 = moptimize_util_userinfo(M, 6)
sel3 = moptimize_util_userinfo(M, 7)
D = moptimize_util_userinfo(M, 8)
id = moptimize_util_userinfo(M, 9)

e = y - xb
e1 = NULL
st_select(e1,e,sel1)
e2 = NULL
st_select(e2,e,sel2)
e3 = NULL
st_select(e3,e,sel3)

info = panelsetup(id,1)
nc = rows(info)
for(i=1; i<=503; i++) {
z1i = panelsubmatrix(z1,i,info)
z2i = panelsubmatrix(z2,i,info)
z3i = panelsubmatrix(z3,i,info)
e1i = panelsubmatrix(e1,i,info)
e2i = panelsubmatrix(e2,i,info)
e3i = panelsubmatrix(e3,i,info)
zi = blockdiag(z1i, blockdiag(z2i,z3i))
ei = e1i\e2i\e3i
D = D + zi'*ei*ei'*zi
}
Wopt = qrinv(D)
m = z'*e
q = m'*Wopt**m
}
/// initialise moptimize
M = moptimize_init()
moptimize_init_evaluator(M, &oiv_gmm())
moptimize_init_evaluatortype(M, "d0")
moptimize_init_depvar(M, 1, y)
moptimize_init_eq_indepvars(M, 1, x)
moptimize_init_userinfo(M, 1, (z1))
moptimize_init_userinfo(M, 2, (z2))
moptimize_init_userinfo(M, 3, (z3))
moptimize_init_userinfo(M, 4, (z))
moptimize_init_userinfo(M, 5, (sel1))
moptimize_init_userinfo(M, 6, (sel2))
moptimize_init_userinfo(M, 7, (sel3))
moptimize_init_userinfo(M, 8, (D))
moptimize_init_userinfo(M, 9, (id))
moptimize_init_eq_cons(M, 1, "off")
moptimize_init_eq_coefs(M, 1, (b0))
moptimize_init_which(M, "min")
moptimize_init_technique(M, "nr")
moptimize(M)
moptimize_result_display(M)
b_gmm = moptimize_result_coefs(M)
b_gmm
*** get GMM estimes
b_gmm = moptimize_result_coefs(M)'
end


The following error message shows up: nonpointer found where pointer required. So far what I have deduced is that it maybe a problem in the step where I'm calculating the cluster robust GMM weight using panelsubmatrix. What would possibly be the correct way to approach this ?