pro pe_grid, delong, dpa, label = label, charsize = charsize, _extra = $
             _extra

;+
; NAME:
;	PE_GRID
;
;
; PURPOSE:
;	Add a grid of elongation and position angle to a SMEI
;	aitoff plot
;
;
; CATEGORY:
;	utils
;
;
; CALLING SEQUENCE:
;	pe_grid[, delong, dpa]
;
;
; OPTIONAL INPUTS:
;	delong	int	The step in elongation angle.
;	dpa	int	The step in position angle.
;
;
; KEYWORD PARAMETERS:
;	/label			If set, then label the grid.
;	charsize	Float	Set a size for the labels (ignored if
;				label is not set.
;	Any key accepted by PLOTS will be passed through.
;
; RESTRICTIONS:
;	Steps will be rounded to the nearest whole degree, PA=0 and 90
;	will always be drawn.
;
; MODIFICATION HISTORY:
;	Original: 17/6/03; SJT
;	Add delong and dpa arguments: 24/7/03; SJT
;-


if n_params() ne 2 then dpa = 30 else dpa = round(dpa)
if n_params() eq 0 then delong = 30 else delong = round(delong)

a90 = 0b

; Elongation "contours".

for elong = delong, 179, delong do begin
    if elong eq 90 then begin
        a90 =1b
        continue
    endif else if elong lt 90 then lin = $
      sin((findgen(2*elong+1)-float(elong))*!dtor)*elong/sin(elong*!dtor) $
    else lin = 180.- $
      (180-elong)*sin(findgen(180-elong+1)*!dtor)/sin(elong*!dtor)

    qd_elong, float(elong), lin, lat, lout
    aitoff, lout, lat, x, y
    plots, x, y, _extra = _extra

    if elong gt 90 then begin
        qd_elong, float(elong), -lin, lat, lout
        aitoff, lout, lat, x, y
        plots, x, y, _extra = _extra

    endif
endfor

; Position angle traces

lin = findgen(361)-180

for pa = dpa, 89, dpa do begin
    qd_posang, float(pa), lin, lat, lout
    aitoff, lout, lat, x, y
    plots, x, y, _extra = _extra
endfor

; Add the axes, boundary and if needed 90 degree elongation with
; aitoff_grid.

if a90 then dl = 90 else dl = 180
aitoff_grid, dl, 90, /noclip, _extra = _extra

if keyword_set(label) then begin
    dy = .5
    for elong = delong, 179, delong do begin
        aitoff, elong, 0., x, y ; Use longitude=elongation at
                                ; latitude=0
        xyouts, x, y+dy, string(elong, format = "(I0)"), align = 0.5, $
                charsize = charsize
        xyouts, -x, y+dy, string(elong, format = "(I0)"), align = 0.5, $
                charsize = charsize
    endfor

    for pa = dpa, 89, dpa do begin
        qd_posang, pa, 85., lat, lon
        aitoff, lon, lat, x, y
        x = x[0]
        y = y[0]
        xyouts, x, y, string(pa, format = "(I0)"), align = 0.5, $
                charsize = charsize
        xyouts, x, -y, string(180-pa, format = "(I0)"), align = 0.5, $
                charsize = charsize
        if pa ne 0 then begin
            xyouts, -x, -y, string(180+pa, format = "(I0)"), align = 0.5, $
                charsize = charsize
            xyouts, -x, y, string(360-pa, format = "(I0)"), align = 0.5, $
                charsize = charsize
        endif
    endfor
endif

end
