function hsi_annsec2xy,annsecimage, image_obj,  xgrid, ygrid, $
this_harmonic=this_harmonic, this_det_index=this_det_index, $
max_value=max_value, min_value=min_value, noquintic=noquintic,$
limits=limits, modpat_ptr=modpat_ptr, gs=gs, $
finescale=finescale,missing=missing

default, finescale, 0
if  keyword_set( annsecimage ) then begin

if size(modpat_ptr,/tname) ne 'POINTER' then $
modpat_ptr = image_obj-> getdata(class_name='hsi_modul_pattern' )
this_modpat_ptr = modpat_ptr

quintic = keyword_set( noquintic ) ? 0 : 1 ;fixed noquintic, ras, 17-mar-2008

checkvar, this_harmonic, 0

case  1 of
    size(/tname, image_obj) eq 'OBJREF' : begin
        valid= where(image_obj->get(/det_index_mask))
        this_modpat_ptr = (image_obj->getdata(class_name='hsi_modul_pattern'))[valid[0]]
        end
    else: begin
        valid = 0
        while size(/tname,*this_modpat_ptr[valid]) ne 'STRUCT' do valid = valid+1
        this_modpat_ptr = this_modpat_ptr[valid]
        end
    endcase

if exist(this_det_index) and n_elements(this_modpat_ptr) gt 1 then $
    this_modpat_ptr = this_modpat_ptr[ this_det_index, this_harmonic ]

hsi_annsec_coord, image_obj, x, y, rmap, thetamap, modpat_ptr = this_modpat_ptr
if n_elements(limits) ne 4  then limits = hsi_fovbox( image_obj, modpat_ptr = this_modpat_ptr)

if not keyword_set(gs) then $
    gs = (*this_modpat_ptr).pixel_size * (*this_modpat_ptr).pixel_scale
gs = gs + fltarr(2)
if not keyword_set(missing) then missing = avg( annsecimage)

nx = (limits[2]-limits[0])/gs[0] +1
ny = (limits[3]-limits[1])/gs[1] +1
aimage = annsecimage
if keyword_set(finescale) then begin
    scl = long(keyword_set(finescale) > 2)*1.0
    rmap_dim = size(/dim, annsecimage)*scl
    x = rebin(x, rmap_dim)
    y = rebin(y, rmap_dim)
    aimage = rebin(annsecimage, rmap_dim)
    ;aimage = congrid(annsecimage, rmap_dim[0],rmap_dim[1],/inter)
    endif

triangulate, x, y, tr
out = trigrid( x, y, aimage,  tr, gs, limits[*], missing=missing,$
    xgrid = xgrid, ygrid=ygrid, quintic=quintic, $
    max_value=max_value, min_value=min_value)

;Check limits on xgrid and ygrid
in_rangex = where( (xgrid gt (limits[0]-0.1*gs[0])) $
           and (xgrid lt (limits[2]+0.1*gs[0])), n_in_rangex)

if n_in_rangex lt n_elements(xgrid) then begin
    xgrid = xgrid[in_rangex]
    out = out[in_rangex, *]
    endif
in_rangey = where( (ygrid gt (limits[1]-0.1*gs[1])) $
           and (ygrid lt (limits[3]+0.1*gs[1])), n_in_rangey)

if n_in_rangey lt n_elements(ygrid) then begin
    ygrid = ygrid[in_rangey]
    ;out = out[in_rangey, *] - wrong. selecting on x and not y. fix below, ras 17-feb-2005
    out = out[*, in_rangey]
    endif

return, out
endif
return, annsecimage
end