; NAME:
;   rnplot.pro (v1.2)
;
; PURPOSE:
;   plots readnoise results
;
; CALLING SEQUENCE:
;   rnplot, noisefile, plotfile [, gtitle[, minexp]]
;
; INPUTS:
;   noisefile       - textfile containing noise values output from
;                     readnoise_reduce.pro
;   plotfile        - base file name (no extension should be specified) of
;                     output plots.  PS and JPEG plots are generated, and the
;                     proper file extension for each is appended to this
;                     variable when creating the files.
;
; KEYWORD PARAMETERS:
;   gtitle          - text string to use in plot title.  The value of this
;                     keyword is appended to the text 'Read noise for ' or
;                     'Total noise for ' (depending on the value of the
;                     minexp keyword) and the resulting string is used as the
;                     plot title.  Value defaults to the detector name if it
;                     is not set.
;   minexp          - this keyword is set to indicate that the values in the
;                     input file represent total noise in 1000 seconds instead
;                     of read noise.
;
; EXAMPLE
;   IDL> rnplot, 'totalnoise.txt', 'totalnoise_plot', /minexp
;
; REFERENCE:
;
; MODIFICATION HISTORY:
;   Written by:
;       Ernie Morse, IDTL
;   Modified by:
;       Bernie Rauscher, IDTL, April 23, 2003 (v1.1)
;           Added minexp keyword.
;       Ernie Morse, IDTL, February 6, 2004 (v1.2)
;           Edited to insure compliance with IDTL coding standards.
;
Pro rnplot, noisefile, plotfile, gtitle = gtitle, minexp = minexp

    ; declare empty string variables for input from file
    detector = (ref_ver = (ref_type = (gdate = (region = ''))))

    ; read in parameters from noisefile
    openr, nflun, noisefile, /get_lun
    readf, nflun, detector, format = '(A)'
    readf, nflun, ref_ver, format = '(A)'
    readf, nflun, ref_type, format = '(A)'
    readf, nflun, gdate, format = '(A)'
    readf, nflun, region, format = '(A)'
    free_lun, nflun

    ; use detector name in plot title if not otherwise specified by the
    ; gtitle keyword.
    if (not keyword_set(gtitle)) then begin
        gtitle = detector
    endif

    ; read values from noisefile
    ; s = number of Fowler pairs
    ; t = detector temperature
    ; n = read noise value
    readcol, noisefile, s, t, n, format = 'I, A, D', skipline = 5

    ; determine the set of sample pair values present in the file
    us = uniq(s, sort(s))
    samples = s[us]

    ; determine the number of detector temperatures present in the file
    ; this assumes that every detector temperature in the file has noise
    ; values for all of the values of samples
    ntemps = n_elements(t) / n_elements(samples)

    ; find the detector temperature values
    x = indgen(n_elements(t))
    temps = t[where(x mod n_elements(samples) eq 0)]

    ; make an array to hold all of the noise values in the file
    ; each row holds all of the noise results for a single detector temperature
    noise = dblarr(n_elements(samples), ntemps)

    ; fill the noise array with the values read from the file
    for i = 0, ntemps - 1 do begin
        start = i * n_elements(samples)
        fin = start + n_elements(samples) - 1
        noise[*, i] = n[start:fin]
    endfor

    ; determine how many plots will be needed, assuming we want no more than
    ; three temperatures per plot
    nplots = ceil(n_elements(temps)/3.0)

    ; save the current device name so it can be restored at the end of the
    ; routine
    dname = !D.NAME

    ; make the required number of plots, writing out each one as both a PS
    ; and JPEG file.
    for j = 0, nplots - 1 do begin

        ; make plot name strings
        jpgfile = plotfile + strtrim(string(j), 2) + '.jpg'
        psfile = plotfile + strtrim(string(j), 2) + '.ps'

        ; set foreground and background plot colors
        bg = 255
        fg = 0

        ; determine plot symbols to use to distinguish between the noise
        ; values for different temperatures
        psyms = [-2, -4, -5, -6, -7]

        ; set plot ranges
        ymin = 0
        ymax = max(noise) * 1.05
        xmin = 0
        xmax = max(samples) + 1

        ; this loop executes twice, once to make a PS plot and once to make a
        ; JPEG plot
        for outcount = 0, 1 do begin

            ;first set up for landscape Postscript plots
            if outcount eq 0 then begin
                set_plot, 'ps'
                !p.font = -1
                device, filename = psfile, /landscape

                ; fsub is filename to be written at bottom of plot
                fsub = psfile

                ; set plot margins and # of tick marks
                !Y.MINOR = 10
                !y.margin = [6, 2]
                !x.margin = [14, 4]

                ; set line and text characteristics for publication quality
                !P.CHARSIZE = 1.2
                !P.CHARTHICK = 4.
                !X.THICK = 8.
                !Y.THICK = 8.
                !P.THICK = 8.
                !P.MULTI = 0
                !P.TICKLEN = 0.03
                symsize = 1.5
                filenamecharsize = 1.1

            endif else begin

                ; this is for JPEG, where the plot will be written to the
                ; z-buffer in memory and then converted to JPEG format.
                set_plot, 'z'
                device, set_resolution = [8000, 6000]
                device, set_font = 'Courier'

                ; fsub is filename to be written at bottom of plot
                fsub = jpgfile

                ; set plot margins and # of tick marks
                !Y.MINOR = 10
                !y.margin = [6, 4]
                !x.margin = [14, 4]

                ; set line and text characteristics for publication quality
                !P.CHARSIZE = 10
                !P.CHARTHICK = 15.
                !X.THICK = 20.
                !Y.THICK = 20.
                !P.THICK = 20.
                symsize = 10.
                filenamecharsize = 8.
            endelse

            ; define titles
            if (keyword_set(minexp)) then begin
                xtitle = "Number of Fowler Pairs"
                ytitle = "Read noise (ADU)"
                title = "Read Noise for " + gtitle + ' with continuous reads'
            endif else begin
                xtitle = "Number of Fowler Pairs"
                ytitle = "Total noise (ADU)"
                title = "Total Noise for " + gtitle + ' in 1000 seconds'
            endelse

            ; draw plot
            ; use a logarithmic scale if the noise values range over more than
            ; a decade
            if (max(noise) / min(noise) gt 10.0) then begin
                plot, samples, noise[*, 0], yrange = [ymin, ymax], $
                        xrange = [xmin, xmax], /nodata, /ylog, xstyle = 1, $
                        ystyle = 1, color = fg, background = bg, $
                        xtitle = xtitle, ytitle = ytitle, title = title, $
                        charsize = 1.25 * !P.CHARSIZE
            endif else begin
                plot, samples, noise[*, 0], yrange = [ymin, ymax], $
                        xrange = [xmin, xmax], /nodata, xstyle = 1, ystyle = 1,$
                        color = fg, background = bg, xtitle = xtitle, $
                        ytitle = ytitle, title = title, $
                        charsize = 1.25 * !P.CHARSIZE
            endelse

            ; determine the highest temperature value to be shown on the
            ; current plot
            if (j eq nplots - 1) then begin
                lasttemp = n_elements(temps) - 1
            endif else begin
                lasttemp = j * 3 + 2
            endelse

            ; determine the range of temperatures to be shown on the current
            ; plot
            tempslice = temps[j * 3:lasttemp]

            ; determine locations for annotation showing plot legend
            ax = [max(samples) * 0.7]
            ay = (findgen(n_elements(tempslice) + 1) * (-0.05) + 0.9) $
                  * max(noise) * 1.05

            ; draw curves for each temperature
            for i = 0, n_elements(tempslice) - 1 do begin

                ; plot the date
                oplot, samples, noise[*, (j * 3) + i], psym = psyms[i mod 5], $
                        color = fg, symsize = symsize

                ; plot symbols in legend
                oplot, ax, ay[i:i], psym = psyms[i mod 5], color = fg, $
                        symsize = symsize

                ; draw annotation next to symbols to explain which symbols go
                ; with each temperature value
                xyouts, ax + (ax * 0.05), ay[i], '= ' + temps[(j * 3) + i] $
                        + ' K', color = fg
            endfor

            ; plot the curve showing the maximum noise value / sqrt(# of pairs)
            x = (findgen(max(samples) * 2) + 1) / 2
            oplot, x, noise[0] / sqrt(x), linestyle = 2, $
                    thick = !P.THICK * 1.5,color = fg, symsize = symsize

            ; put an entry for the sqrt(n) curve in the legend
            oplot, [ax[0] - (ax[0] * 0.02), ax[0] + (ax[0] * 0.02)], $
                    [ay[i], ay[i]], linestyle = 2, color = fg, $
                    thick = !P.THICK * 1.5
            xyouts, ax + (ax*0.05), ay[i], '= 1/sqrt(n)', color = fg

            ; annotate the plot with descriptive information
            xyouts, 1, 0.04 * (ymax - ymin) + ymin, 'Data obtained ' + gdate, $
                    color = fg
            xyouts, 1, 0.07 * (ymax - ymin) + ymin, 'Refsub Version: ' $
                    + ref_ver, color = fg
            xyouts, 1, 0.10 * (ymax - ymin) + ymin, 'Refsub Type: ' + ref_type,$
                     color = fg
            xyouts, 1, 0.13 * (ymax - ymin) + ymin, 'Array region: ' + region, $
                    color = fg
            xyouts, 1.0, 40.0, fsub, color = fg, charsize = filenamecharsize, $
                    charthick = (!p.charthick / 1.5), /device

            ;For the JPEG plot, the plot image must be read in from memory and
            ; written out to a file
            if (outcount eq 1) then begin
                jpgimg = tvrd()
                write_jpeg, jpgfile, $
                        congrid(jpgimg, 1600, 1200, /center, /interp), $
                        quality = 100
            endif

            ;finish up by closing device
            device, /close

        endfor
    endfor

    ; restore the plot device to the original value
    set_plot, dname

End
