; written by Dr. Tim Mitchell, Tyndall Centre
; written on 15th March 2002
; last modified 21.03.02 

;*******************************************************************************
; plot subroutine
; ForceAxis:0=n,1=y  QScreenFile:0=screen,1=file  QKeyN:0=0,1=1,2=NPlot

pro UpdatePlotTS,YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec, $
	PlotCorners,KeyCorners,QKeyN,QScreenFile,ForceAxis,Title

if (QScreenFile EQ 0) then begin
  BackCol=0 & AxisCol=255
endif else begin
  BackCol=255 & AxisCol=0
endelse

DimLineSpec = size(LineSpec)
NPlot = DimLineSpec(1)
NFile = DimLineSpec(2)
NPer  = 17
DimData = size(Data)
NYear = DimData(2)

erase, BackCol

if (TopBarSpec[0,0] NE -1) then begin
 if (QScreenFile EQ 1) then begin
  read_jpeg, '/cru/tyn1/f709762/goglo/tyn-logo-torok.jpg', Logo, LogoCT, $
  		colors=256, dither=1, /two_pass_quantize
  tvlct, Red,Green,Blue, /get					; get old colors
  tvlct, LogoCT(*,0), LogoCT(*,1), LogoCT(*,2)
  tv, Logo, TopBarSpec[0,0],TopBarSpec[0,1],xsize=TopBarSpec[0,2], $
  		ysize=TopBarSpec[0,3],/normal
  tvlct, Red,Green,Blue						; restore old colors
 endif else begin
  xyouts,TopBarSpec[0,0],TopBarSpec[0,1],'logo',/normal,alignment=0,charsize=1, $
  		charthick=1,font=5
 endelse
endif

if (TopBarSpec[1,0] NE -1) then $
  xyouts,TopBarSpec[1,0],TopBarSpec[1,1],Title,/normal,alignment=0.5, $
  		charsize=2.5,charthick=3,font=5

if (TopBarSpec[2,0] NE -1) then begin
  Author = 'Tim Mitchell'
  DateTime  = systime ()
  DateStamp = strmid(DateTime,4,7) + strmid(DateTime,20,4)
  xyouts,TopBarSpec[2,0],TopBarSpec[2,1],Author,/normal,alignment=1, $
  		charsize=1,charthick=1,font=5
  xyouts,TopBarSpec[2,2],TopBarSpec[2,3],DateStamp,/normal,alignment=1, $
  		charsize=1,charthick=1,font=5
endif

XKey=0 & XEntry=-1.0
for XPlot = 0, (NPlot-1) do begin
  XMin=PlotSpec(XPlot,0,0) & XMax=PlotSpec(XPlot,0,1)
  if (ForceAxis EQ 0) then begin
    DataNAN = Data & Missing = where(DataNAN EQ -999.0, Count) 
    if (Count GT 0) then DataNAN(Missing) = !Values.F_NaN
    YMin=min(DataNAN,/nan,max=YMax)
  endif else begin
    YMin=PlotSpec(XPlot,1,0) & YMax=PlotSpec(XPlot,1,1)
  endelse
  
;  XTickLen=-0.02 & if (PlotSpec[XPlot,0,4] EQ 1) then XTickLen=1.0
;  YTickLen=-0.02 & if (PlotSpec[XPlot,1,4] EQ 1) then YTickLen=1.0
  
  plot, YearAD[*], Data[0,*,0], $				; random line
  	Background=BackCol,Color=AxisCol,$			; colour		
  	XStyle=(ForceAxis+8-(PlotSpec(XPlot,0,3)*8)), $		; x axis labelled on both ends?
  	YStyle=(ForceAxis+8-(PlotSpec(XPlot,1,3)*8)), $		; y axis labelled on both ends?
  	Title=PlotLabel[XPlot,2],$				; plot title
  	XTitle=PlotLabel[XPlot,0],$				; x axis title
  	YTitle=PlotLabel[XPlot,1],$				; y axis title  	
  	XTicks=PlotSpec[XPlot,0,2],$				; x tick marks  	
  	YTicks=PlotSpec[XPlot,1,2],$				; y tick marks  	
  	XTickLen=PlotSpec[XPlot,0,4], $		; x,y gridding: -0.02=default
  	YTickLen=PlotSpec[XPlot,1,4], $		; 1.0=boxy with grid lines
  	XRange=[XMin,XMax],YRange=[YMin,YMax],$			; axis limits
  	/NoData,font=5,position=PlotCorners[XPlot,*],/NoErase
  	  	
  for XFile=0,(NFile-1) do begin				; plot individual bar series
    for XPer=0,(NPer-1) do begin
      if (LineSpec(XPlot,XFile,XPer,0) EQ 66) then begin
       BarBase = LineSpec(XPlot,XFile,XPer,1)
       BarColor = AxisCol & if (QScreenFile EQ 1) then BarColor = LineSpec(XPlot,XFile,XPer,3)
       
       for XYear = 0, NYear-1 do begin
        if (YearAD(XYear) GT XMin AND YearAD(XYear) LT XMax) then begin
         if (Data[XFile,XYear,XPer] NE -999.0) then begin
          BarYear = float(YearAD(XYear))
          RefsX = [BarYear-0.5,BarYear-0.5,BarYear+0.5,BarYear+0.5,BarYear-0.5]
          RefsY = [BarBase,Data[XFile,XYear,XPer],Data[XFile,XYear,XPer],BarBase,BarBase]
          polyfill, RefsX,RefsY,color=BarColor
         endif
        endif
       endfor
      endif
    endfor
  endfor
  
  for XFile=0,(NFile-1) do begin				; plot individual lines
    for XPer=0,(NPer-1) do begin
      if (LineSpec(XPlot,XFile,XPer,0) LT 66) then begin
       LineColor = AxisCol & if (QScreenFile EQ 1) then LineColor = LineSpec(XPlot,XFile,XPer,3)
       DataNAN = Data(XFile,*,XPer) & Missing = where(DataNAN EQ -999.0, Count) 
       if (Count GT 0) then DataNAN(Missing) = !Values.F_NaN
       
       oplot, YearAD[*], DataNAN, $				; plot line
        PSym=LineSpec(XPlot,XFile,XPer,0), $			; symbol
        LineStyle=LineSpec(XPlot,XFile,XPer,1), $		; line style
        Thick=LineSpec(XPlot,XFile,XPer,2), $			; line thickness
        Color=LineColor						; colour
      endif
    endfor
  endfor
      
  if (QKeyN GT 0) then begin					; plot key
   if (QKeyN GE 2) then begin
   	XKey=XPlot & XEntry=-1.0
   endif
   
   for XFile=0,(NFile-1) do begin
    for XPer=0,(NPer-1) do begin
      if (KeyLabel(XPlot,XFile,XPer) NE '') then begin
        LineColor = AxisCol & if (QScreenFile EQ 1) then LineColor = LineSpec(XPlot,XFile,XPer,3)
        XEntry=XEntry+1.0
        RefY=KeyCorners[XKey,1]-(XEntry*KeyCorners[XKey,3])
        
        if (LineSpec(XPlot,XFile,XPer,0) EQ 66) then begin
          RefY0=RefY+(KeyCorners[XKey,3]*0.25) & RefY1=RefY-(KeyCorners[XKey,3]*0.25)
          RefX0=KeyCorners[XKey,0] & RefX1=(((KeyCorners[XKey,2]-KeyCorners[XKey,0])*0.8)+KeyCorners[XKey,0])
          polyfill,[RefX0,RefX0,RefX1,RefX1,RefX0],[RefY0,RefY1,RefY1,RefY0,RefY0],Color=LineColor,/normal          
        endif else if (LineSpec(XPlot,XFile,XPer,0) NE 99) then begin
          if (LineSpec(XPlot,XFile,XPer,0) GT 0) then begin	; symbols only
            plots,[KeyCorners[XKey,0]],$
                [RefY],PSym=LineSpec(XPlot,XFile,XPer,0),LineStyle=LineSpec(XPlot,XFile,XPer,1),$
                Thick=LineSpec(XPlot,XFile,XPer,2),Color=LineColor,/normal
          endif else begin					; lines, with or without symbols
            plots,[KeyCorners[XKey,0],(((KeyCorners[XKey,2]-KeyCorners[XKey,0])*0.8)+KeyCorners[XKey,0])],$
                [RefY,RefY],PSym=LineSpec(XPlot,XFile,XPer,0),LineStyle=LineSpec(XPlot,XFile,XPer,1),$
                Thick=LineSpec(XPlot,XFile,XPer,2),Color=LineColor,/normal
          endelse
        endif
        
        xyouts,KeyCorners[XKey,2],(RefY-(KeyCorners[XKey,3]*0.25)), $
               KeyLabel(XPlot,XFile,XPer),/normal,alignment=0,charsize=1,charthick=1,font=5
      endif
    endfor
   endfor
  endif
endfor

end

;*******************************************************************************
; main program

;***************************************
; INITIALISATION

GivenFile="" & Title="" & Year0=0 & Year1=0 & NPer=17 & PlotOrder=0 & Label=""
XSym=99.0 & XStyle=99.0 & XThick=99.0 & XColor=99.0 & XBase=99.0 
ValueFloat=0.0 & Width2Height=0.0 & XCol=0 & MissVal=-999.0

MonLabel=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','MAM','JJA','SON','DJF','ann']
MonthName=['January','February','March','April','May','June','July','August','September','October', $
		'November','December']

;***************************************
; FILE SPECS

print, "  > PLOTTS.PRO: plot to screen and .eps"
print, "  > Plot in colour (=0) or black+white (=1) ?"
read, QColBW
if (QColBW EQ 0) then loadanyct, 34 
if (QColBW EQ 1) then loadanyct, 0
Black=0 & Grey=254 & White=255

print, "  > Enter the number of .per, .ann files to load: "
read, NPerFile, NAnnFile

NFile = NPerFile + NAnnFile

LoadYear0 = intarr(NFile) & LoadYear1 = intarr(NFile)
LoadFile = strarr(NFile)

print, "  > Enter file paths manually (=0) or in batches (=1): "
read, QManBatch

if (NPerFile GT 0) then begin
  if (QManBatch EQ 0) then begin
    print, "  > Enter each .per file in turn (only prompted for errors): "
    for XFile = 0, NPerFile-1 do begin
      read, GivenFile
      LoadFile(XFile) = GivenFile
      LoadPer, CallFile=GivenFile, Year0=Year0, Year1=Year1
      LoadYear0(XFile)=Year0 & LoadYear1(XFile)=Year1
    endfor
  endif else begin
    print, "  > Specify .per files." & BatchFileN=0
    while (BatchFileN NE NPerFile) do begin
      GetFileBatch, BatchFiles, BatchFileN
      if (BatchFileN NE NPerFile) then print, "  > Bad number of files in batch. Retry."
    endwhile
    for XFile = 0, NPerFile-1 do begin
      LoadFile(XFile) = BatchFiles(XFile)
      LoadPer, CallFile=LoadFile(XFile), Year0=Year0, Year1=Year1
      LoadYear0(XFile)=Year0 & LoadYear1(XFile)=Year1
    endfor
  endelse
endif

if (NAnnFile GT 0) then begin
  if (QManBatch EQ 0) then begin
    print, "  > Enter each .ann file in turn (only prompted for errors): "
    for XFile = NPerFile, NFile-1 do begin
      read, GivenFile
      LoadFile(XFile) = GivenFile
      LoadAnn, CallFile=GivenFile, Year0=Year0, Year1=Year1
      LoadYear0(XFile)=Year0 & LoadYear1(XFile)=Year1
    endfor
  endif else begin
    print, "  > Specify .ann files." & BatchFileN=0
    while (BatchFileN NE NAnnFile) do begin
      GetFileBatch, BatchFiles, BatchFileN
      if (BatchFileN NE NAnnFile) then print, "  > Bad number of files in batch. Retry."
    endwhile
    for XFile = NPerFile, NFile-1 do begin
      LoadFile(XFile) = BatchFiles(XFile)
      LoadAnn, CallFile=LoadFile(XFile), Year0=Year0, Year1=Year1
      LoadYear0(XFile)=Year0 & LoadYear1(XFile)=Year1
    endfor
  endelse
endif
					; identify unique elements of file names
if (QManBatch EQ 1 AND NFile GT 1 AND (NAnnFile EQ 0 OR NPerFile EQ 0)) then begin
    QUniqueName = 1
    UniqueName = strarr(NFile) & UniqueName(*) = 'unknown'
    File0 = strtrim(LoadFile(0),2) 
    if (NAnnFile EQ 0) then File1 = strtrim(LoadFile(NPerFile-1),2)
    if (NPerFile EQ 0) then File1 = strtrim(LoadFile(NAnnFile-1),2)
    Len0 = strlen(File0) & Len1 = strlen(File1)

    XCommonPre = 0 & XChar = 0		; find identity of Pre common element
    while (XCommonPre GE 0) do begin
      XChar = XChar + 1
      XCommonPre = strpos(File1,strmid(File0,0,XChar))
    endwhile
    CommonPreLen = XChar-1
    
    XCommonPost = 0 & XChar = 0		; find identity of Post common element
    while (XCommonPost GE 0) do begin
      XChar = XChar + 1
      XCommonPost = strpos(File1,strmid(File0,XChar,XChar+1,/reverse_offset),/reverse_search)
    endwhile
    CommonPostLen = XChar
    
    for XFile = 0, NFile-1 do begin
      ThisFile = strtrim(LoadFile(XFile),2)
      ThisFileLen = strlen(ThisFile)
      UniqueName(XFile) = strmid(ThisFile, $
      				CommonPreLen,(ThisFileLen-CommonPostLen-CommonPreLen))
      ThisName = strtrim(UniqueName(XFile),2)
      ThisNameLen = strlen(ThisName)
      for XChar = 0, ThisNameLen-1 do begin
        ThisName = strtrim(UniqueName(XFile),2)
        ThisChar = strmid(ThisName,XChar,1)
        if (ThisChar EQ '_') then UniqueName(XFile) = strmid(ThisName,0,XChar) + ' ' + $
        			strmid(ThisName,XChar+1,ThisNameLen-XChar-1)
      endfor
    endfor
endif else begin
    QUniqueName = 0
endelse

print, "  > Enter the min,max okay values (-999=ignore): "
read, OkayMin,OkayMax

Year0 = min(LoadYear0) & Year1 = max(LoadYear1) & NYear=Year1-Year0+1
YearAD=indgen(NYear) & YearAD(*)=YearAD(*)+Year0
X1961=-999 & if (Year0 LE 1961) then X1961=1961-Year0
X1990=-999 & if (Year1 GE 1990) then X1990=1990-Year0

print, "  > Enter the period of interest: beg,end (-999=ignore): "
read, YearADBeg,YearADEnd

;***************************************
; PICTURE SPECS

print, "  > Include top info bar (0=no,1=yes) ?"
read, QTopBar

if (QTopBar EQ 1) then begin
  print, "  > Include logo,title,attribution (each: 0=no,1=yes) ?"
  read, QLogo,QTitle,QAttrib
  
  if (QTitle EQ 1) then begin
    print, "  > Enter the title for the top info bar: "
    read, Title
    GiveSymbol, Title
  endif
endif else begin
  QLogo=0 & QTitle=0 & QAttrib=0
endelse

print, "  > Enter the number of plots: "
read, NPlot

if            (NPlot EQ 1) then begin
  NRow=1 & NCol=1
endif else if (NPlot EQ 2) then begin
  NRow=1 & NCol=2
endif else if (NPlot EQ 4) then begin
  NRow=2 & NCol=2
endif else if (NPlot EQ 6) then begin
  NRow=2 & NCol=3
endif else if (NPlot EQ 12) then begin
  NRow=4 & NCol=3
endif else begin
  print, "  > Enter the number of rows, columns: "
  read, NRow, NCol
endelse

print, "  > Enter the width/height ratio for individual plots: "
read, Width2Height

print, "  > Allow space for no axis (=0) X (=1), Y (=2), both (=3) labels ? "
read, QSpaceLabels

print, "  > Key options: 0=none,1=one,2=each plot "
read, QKeyN
if (NPlot EQ 1 AND QKeyN EQ 2) then QKeyN = 1

;***************************************
; FIGURE DIMENSIONS

print, "  > Multiplier for figure size (default=1): "
read, PlotHeightMultiplier
PlotHeight = 150.0 * PlotHeightMultiplier

TopBarHeight = 30.0 & KeyWidth = 80.0		; basic figure dimensions
XAxisIndent = 25.0 & YAxisIndent = 25.0 & TopBarIndent = 5.0 
KeyIndent = 5.0 & KeyLineLen = 10.0 & KeyEntryGap = 15.0
XPixels = 10000 & YPixels = 10000 

if (QSpaceLabels EQ 1 OR QSpaceLabels EQ 3) then YAxisIndent = YAxisIndent + 12.0
if (QSpaceLabels EQ 2 OR QSpaceLabels EQ 3) then XAxisIndent = XAxisIndent + 12.0

while (XPixels GT 900 OR YPixels GT 700) do begin
  YPixels = (float(NRow)*(PlotHeight+(YAxisIndent*2))) + $
  		(float(QTopBar)*TopBarHeight)	; calc overall figure size
  XPixels = float(NCol)*((PlotHeight*Width2Height)+(XAxisIndent*2))
  if (QKeyN EQ 1) then XPixels = XPixels + KeyWidth
  if (QKeyN EQ 2) then XPixels = XPixels + (float(NCol)*KeyWidth)
  
  if (YPixels GT 700) then begin
    PlotHeight = ((690.0-(float(QTopBar)*TopBarHeight))/float(NRow)) - (YAxisIndent*2)
  endif else if (XPixels GT 900) then begin
    if (QKeyN EQ 1) then begin
    	PlotHeight = (((890.0-KeyWidth)/float(NCol))-(XAxisIndent*2)) * (1.0/Width2Height)
    endif else if (QKeyN EQ 2) then begin
    	PlotHeight = (((890.0-(float(NCol)*KeyWidth))/float(NCol))-(XAxisIndent*2)) $
    			* (1.0/Width2Height)
    endif
  endif
endwhile

InsideFrame = [0.0,0.0,1.0,1.0]				; calc individual plot corners
if (QTopBar EQ 1) then InsideFrame[3] = 1.0 - (TopBarHeight/YPixels)
if (QKeyN   EQ 1) then InsideFrame[2] = 1.0 - (KeyWidth/XPixels)
GetCorners,InsideFrame,PlotCorners,NCol,NRow,PlotOrder, $
		XIndent=(XAxisIndent/XPixels),YIndent=(YAxisIndent/YPixels)
if (QKeyN EQ 2) then PlotCorners[*,2] = PlotCorners[*,2] - (KeyWidth/XPixels)

KeyCorners = fltarr(NPlot,4) & KeyCorners(*,*)=-1.0
if            (QKeyN EQ 1) then begin			; calc key corners
  KeyCorners(0,0) = 1.0 - ((KeyWidth-KeyIndent)/XPixels)
;  KeyCorners(0,1) = 1.0 - (((float(QTopBar)*TopBarHeight)+KeyIndent)/YPixels)
  KeyCorners(0,1) = PlotCorners[0,3]
  KeyCorners(0,2) = KeyCorners(0,0) + ((KeyLineLen+KeyIndent)/XPixels)
  KeyCorners(0,3) = KeyEntryGap / YPixels
endif else if (QKeyN EQ 2) then begin
 for XPlot = 0, NPlot-1 do begin
  KeyCorners(XPlot,0) = PlotCorners[XPlot,2] + ((XAxisIndent+KeyIndent)/XPixels)
  KeyCorners(XPlot,1) = PlotCorners[XPlot,3]
  KeyCorners(XPlot,2) = KeyCorners(XPlot,0) + ((KeyLineLen+KeyIndent)/XPixels)
  KeyCorners(XPlot,3) = KeyEntryGap / YPixels
 endfor
endif

TopBarSpec = fltarr(3,4) & TopBarSpec(*,*)=-1.0

if (QLogo EQ 1) then begin						; logo x:y = 834:184
	TopBarSpec(0,1) = (1.0-((TopBarHeight-TopBarIndent)/YPixels))
	TopBarSpec(0,3) = (TopBarHeight-(TopBarIndent*2.0)) / YPixels

	TopBarSpec(0,0) = TopBarIndent/XPixels
	TopBarSpec(0,2) = TopBarSpec(0,3)*YPixels*(834.0/184.0)/XPixels
endif

if (QTitle EQ 1) then TopBarSpec(1,*) = [0.5,(1.0-((TopBarHeight/1.4)/YPixels)),-1,-1]

if (QAttrib EQ 1) then begin
	TopBarSpec(2,0) = 1.0-(TopBarIndent/XPixels)
	TopBarSpec(2,1) = 1.0-((TopBarIndent*2.5)/YPixels)
	TopBarSpec(2,2) = 1.0-(TopBarIndent/XPixels)
	TopBarSpec(2,3) = 1.0-((TopBarHeight-TopBarIndent)/YPixels)
endif

;***************************************
; LOAD DATA

Data = fltarr(NFile,NYear,NPer) & Data(*,*,*)=-999.0
PerLabel = strarr(NFile,NPer) & PerLabel(*,*)=''

if (NPerFile GT 0) then begin
 for XFile = 0, NPerFile-1 do begin
  LoadPer, CallFile=LoadFile(XFile), Data=FileData
  DataYear0=LoadYear0(XFile)-Year0 & DataYear1=LoadYear1(XFile)-Year0
  Data(XFile,DataYear0:DataYear1,*) = FileData(*,*)
  PerLabel(XFile,*)=MonLabel(*)
 endfor
endif

if (NAnnFile GT 0) then begin
 for XFile = NPerFile, NFile-1 do begin
  LoadAnn, CallFile=LoadFile(XFile), Data=FileData, ColHeads=FileHeads
  DimFile=size(FileData) & NFileCol=DimFile(2) 
  if (NFileCol EQ 2) then NFileCol = 1
  DataYear0=LoadYear0(XFile)-Year0 & DataYear1=LoadYear1(XFile)-Year0
  Data(XFile,DataYear0:DataYear1,0:(NFileCol-1)) = FileData(*,0:(NFileCol-1))
  PerLabel(XFile,0:(NFileCol-1))=FileHeads(0:(NFileCol-1))
 endfor
endif

if (YearADBeg NE -999) then begin
  for XYear=0,(NYear-1) do begin
    if (YearAD(XYear) LT YearADBeg) then Data(*,XYear,*) = -999.0
  endfor
endif

if (YearADEnd NE -999) then begin
  for XYear=0,(NYear-1) do begin
    if (YearAD(XYear) GT YearADEnd) then Data(*,XYear,*) = -999.0
  endfor
endif

;***************************************
; INITIALISE FIGURE

PlotLabel=strarr(NPlot,3) & PlotLabel(*,*)=""

PlotSpec=fltarr(NPlot,2,5) & PlotSpec(*,*,*)=0.0 
PlotSpec(*,0,0)=Year0 & PlotSpec(*,0,1)=Year1 & PlotSpec(*,0,4)=-0.03
PlotSpec(*,1,0)=10000.0 & PlotSpec(*,1,1)=-10000.0

LineSpec=fltarr(NPlot,NFile,NPer,4)
LineSpec(*,*,*,0)=99 & LineSpec(*,*,*,1)=0 & LineSpec(*,*,*,2)=1 & LineSpec(*,*,*,3)=White

KeyLabel=strarr(NPlot,NFile,NPer) & KeyLabel(*,*,*)=''

if (OkayMin NE MissVal) then begin
  Missing = where(Data LT OkayMin, Count)
  if (Count GT 0) then Data(Missing) = MissVal
endif

if (OkayMax NE MissVal) then begin
  Missing = where(Data GT OkayMax, Count)
  if (Count GT 0) then Data(Missing) = MissVal
endif

DataNAN = Data 
Missing = where(DataNAN EQ -999.0, Count) 
if (Count GT 0) then DataNAN(Missing) = !Values.F_NaN
YMin=min(DataNAN,/nan,max=YMax)
PlotSpec(*,1,0)=YMin & PlotSpec(*,1,1)=YMax

if (!D.Window EQ -1) then window, /free, xsize=XPixels, ysize=YPixels, $
  		xpos=(1024-(XPixels)), title="time series plot"
set_plot, 'X'
UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,0,Title

;***************************************
; INITIALISATION
;	XSpec: 0=PSym,1=LineStyle,2=Thick,3=Color
;	LineSpec(XPlot,XFile,XPer,XSpec)

if (NPerFile GT 0) then begin
  if (NPlot EQ 4) then begin
    print, "  > Init plots with the seasons (0=no,1=yes) ?"
    read, QInitPer
    if (QInitPer EQ 1) then PlotLabel(0:3) = PerLabel(0,0:3)	; incomplete - see NPerFile=0 section
  endif else if (NPlot EQ 12) then begin
    print, "  > Init plots with the months (0=no,1=yes) ?"
    read, QInitPer
    if (QInitPer EQ 1) then begin
        PlotLabel(0:11,2) = MonthName(0:11)
        PlotSpec (0:11,0,4) = 1 & PlotSpec (0:11,1,4) = 1
  	for XPlot = 0, NPlot-1 do begin
  	  for XFile = 0, NFile-1 do begin
  	    XCol = 0 & if (NFile GT 1) then XCol = (XFile*(252.0/(NFile-1.0)))+1.0
  	    LineSpec(XPlot,XFile,XPlot,0) = 0 & LineSpec(XPlot,XFile,XPlot,1) = 0 
  	    LineSpec(XPlot,XFile,XPlot,2) = 3 & LineSpec(XPlot,XFile,XPlot,3) = XCol
  	  endfor
  	endfor
  	for XFile = 0, NFile-1 do begin
  	  if (QUniqueName EQ 0) then begin
  	    KeyLabel(0,XFile,0) = '0,' + string(XFile,format='(i2)') + ',0'
  	  endif else begin
  	    KeyLabel(0,XFile,0) = UniqueName(XFile)
  	  endelse
  	endfor
    endif
  endif else if (NAnnFile EQ 0 AND (NPerFile MOD NPlot) EQ 0) then begin
    print, "  > Init plots with one col from each file (-1=no,col=yes) ?"
    read, QInitPer
    if (QInitPer GE 0 AND QInitPer LE 16) then begin
      print, "  > How are the files listed relative to the plots (0=seq,1=block) ?"
      print, "  >   seq: plot0,plot1,...,plotN, plot0,plot1,...,plotN, ... "
      print, "  >   blk: plot0,plot0,...,plot0, plot1,plot1,...,plot1, ... "
      read, QSeqBlock

      XPlot=-1 & XRepli=-1 & XCol=QInitPer & NRepli=NFile/NPlot 
      PlotSpec (0:NPlot-1,0,4) = 1 & PlotSpec (0:NPlot-1,1,4) = 1

      for XFile = 0, NFile-1 do begin
        if (QSeqBlock EQ 0) then begin
            XPlot=XPlot+1 & if (XPlot EQ NPlot) then XPlot=0
            XRepli = floor(float(XFile)/float(NPlot))
        endif else begin
            XRepli=XRepli+1 & if (XRepli EQ NRepli) then XRepli=0
            XPlot = floor(float(XFile)/float(NRepli))
        endelse
        
  	if (QColBW EQ 0) then begin
            XColor = 1.0 + (252.0 * (float(XRepli) / (float(NRepli)-1.0)))
  	    LineSpec(XPlot,XFile,XCol,0) = 0 & LineSpec(XPlot,XFile,XCol,1) = 0 
  	    LineSpec(XPlot,XFile,XCol,2) = 3 & LineSpec(XPlot,XFile,XCol,3) = XColor
  	endif else begin
  	    LineSpec(XPlot,XFile,XCol,0) = 0 & LineSpec(XPlot,XFile,XCol,3) = 0
  	    XThick=1 & if (XRepli GT 2) then XThick=4
  	    XStyle = XRepli MOD 3
  	    LineSpec(XPlot,XFile,XCol,1) = XStyle 
  	    LineSpec(XPlot,XFile,XCol,2) = XThick
  	endelse
  	  
  	if (XPlot EQ 0) then begin
  	   if (QUniqueName EQ 0) then begin
  	    KeyLabel(XPlot,XFile,XCol) = '0,' + string(XFile,format='(i2)') + ',0'
  	   endif else begin
  	    KeyLabel(XPlot,XFile,XCol) = UniqueName(XFile)
  	   endelse
  	endif
  	
  	if (PlotLabel(XPlot,2) EQ '') then begin
  	  PlotLabel(XPlot,2) = 'plot ' + string(XPlot,form='(i2)')
  	  if (QUniqueName NE 0) then PlotLabel(XPlot,2) = UniqueName(XFile)
  	  
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'Mid-East') then PlotLabel(XPlot,2)='Middle East'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'NAmerica') then PlotLabel(XPlot,2)='North America'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'CAmerica') then PlotLabel(XPlot,2)='Central America'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'SAmerica') then PlotLabel(XPlot,2)='South America'
  	endif
      endfor
    endif
  endif
endif else begin
  QInitAnn = 0
  if ((NAnnFile mod NPlot) EQ 0) then begin
    print, "  > Initialise by allocating files to columns (0=no,1=yes) ?"
    read, QInitAnn
    if (QInitAnn EQ 1) then begin
  	for XFile = 0, NFile-1 do begin
  	  XPlot = (XFile mod NPlot) 
  	  if (QColBW EQ 0) then begin
  	    XCol = 0 & if (NFile GT 1) then XCol = (252.0*(XFile-XPlot)/NFile)+1.0
  	    LineSpec(XPlot,XFile,0,0) = 0 & LineSpec(XPlot,XFile,0,1) = 0 
  	    LineSpec(XPlot,XFile,0,2) = 3 & LineSpec(XPlot,XFile,0,3) = XCol
  	  endif else begin
  	    LineSpec(XPlot,XFile,0,0) = 0 & LineSpec(XPlot,XFile,0,3) = 0
  	    XThick=1 & XStyle=0
  	    if (XFile GT 2) then XThick=4
  	    if (XFile EQ 1 OR XFile EQ 4) then XStyle=1
  	    if (XFile EQ 2 OR XFile EQ 5) then XStyle=2
  	    LineSpec(XPlot,XFile,0,1) = XStyle & LineSpec(XPlot,XFile,0,2) = XThick
  	  endelse
  	  
  	  if (XFile EQ XPlot) then begin
  	   if (QUniqueName EQ 0) then begin
  	    KeyLabel(XPlot,XFile,0) = '0,' + string(XFile,format='(i2)') + ',0'
  	   endif else begin
  	    KeyLabel(XPlot,XFile,0) = UniqueName(XFile)
  	   endelse
  	  endif
  	endfor
    endif
  endif
  if (QInitAnn EQ 0) then begin
    print, "  > Initialise with one plot to each column (0=no,1=yes,2=reordered) ?"
    read, QInitAnn
    if            (QInitAnn EQ 1) then begin
      ColOrder=indgen(NPlot)
    endif else if (QInitAnn EQ 2) then begin
      ColOrder=intarr(NPlot) & XCol=0
      print, "  > Enter the column to place in each plot, in plot order: "
      for XPlot = 0, NPlot-1 do begin
        read, XCol
        ColOrder(XPlot)=XCol
      endfor
    endif
    
    if (QInitAnn NE 0) then begin
  	for XPlot = 0, NPlot-1 do begin
  	  for XFile = 0, NFile-1 do begin
  	    if (QColBW EQ 0) then begin
  	      XCol = 0 & if (NFile GT 1) then XCol = (XFile*(252.0/(NFile-1.0)))+1.0
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),0) = 0 
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),1) = 0 
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),2) = 3 
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),3) = XCol
  	    endif else begin
  	      XThick=1 & XStyle=0
  	      if (XFile GT 2) then XThick=4
  	      if (XFile EQ 1 OR XFile EQ 4) then XStyle=1
  	      if (XFile EQ 2 OR XFile EQ 5) then XStyle=2
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),0) = 0 
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),1) = XStyle 
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),2) = XThick
  	      LineSpec(XPlot,XFile,ColOrder(XPlot),3) = 0
  	    endelse
  	  endfor
  	endfor
  	for XFile = 0, NFile-1 do begin
  	  if (QUniqueName EQ 0) then begin
  	    KeyLabel(0,XFile,ColOrder(0)) = '0,' + string(XFile,format='(i2)') + ',0'
  	  endif else begin
  	    KeyLabel(0,XFile,ColOrder(0)) = UniqueName(XFile)
  	  endelse
  	endfor
  	for XPlot = 0, NPlot-1 do begin
  	  PlotLabel(XPlot,2) = PerLabel(0,ColOrder(XPlot))
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'Mid-East') then PlotLabel(XPlot,2)='Middle East'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'NAmerica') then PlotLabel(XPlot,2)='North America'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'CAmerica') then PlotLabel(XPlot,2)='Central America'
  	  if (strtrim(PlotLabel(XPlot,2)) EQ 'SAmerica') then PlotLabel(XPlot,2)='South America'
        endfor  	
  	PlotSpec (0:NPlot-1,0,4) = 1 & PlotSpec (0:NPlot-1,1,4) = 1
    endif
  endif
endelse

;***************************************
; MAIN LOOP

QSatisfied = 1

while (QSatisfied NE 0) do begin

;***************************************
; LABEL SPECS
; plot labels (x,y,plot)
; ask for label:
;	XPlot (77=update,88=all,99=end)
;	XAxis,Label

print, "  > SELECT LABELS."

XPlot = 77
while (XPlot NE 99) do begin
  if            (XPlot EQ 77) then begin
  	UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,0,Title
  endif else if (XPlot EQ 88) then begin
        XAxis=-1 & print, "  > Select the axis (0=X,1=Y,2=title) and label for plot: ", XPlot
        while (XAxis LT 0 OR XAxis GT 2) do begin
          read, XAxis, Label
          GiveSymbol, Label
        endwhile
        for XPlot = 0, NPlot-1 do begin
          PlotLabel(XPlot,XAxis) = Label
        endfor
  endif else if (XPlot GE 0 AND XPlot LT NPlot) then begin
        XAxis=-1 & print, "  > Select the axis (0=X,1=Y,2=title) and label: "
        while (XAxis LT 0 OR XAxis GT 2) do begin
          read, XAxis, Label
          GiveSymbol, Label
        endwhile
        PlotLabel(XPlot,XAxis) = Label
  endif

  print, "  > Select a plot (77=update,88=all,99=end):"
  read, XPlot  
endwhile

;***************************************
; LINE SPECS
; identify plot, line and then prescribe details
;	XPlot (77=update,99=end)
;	XFile,XPer
;	XSpec: 0=PSym,1=LineStyle,2=Thick,3=Color

print, "  > SELECT LINES."

XPlot = 77
while (XPlot NE 99) do begin
  if            (XPlot EQ 77) then begin
  	UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,0,Title
  endif else if (XPlot EQ 66) then begin
        if (NFile EQ 1) then begin
          XFile=0 & XPer=-1 & XPlot=-1
          print, "  > Select the plot and time period (0-16): "
          while (XPer LT 0 OR XPer GT 16 OR XPlot LT 0 OR XPlot GE NPlot) do begin
            read, XPlot,XPer
          endwhile
        endif else begin
          XPer=-1 & XFile=-1 & XPlot=-1
          print, "  > Select the plot, file and time period (0-16) to plot: "
          while (XPer LT 0 OR XPer GT 16 OR XFile LT 0 OR XFile GE NFile OR XPlot LT 0 OR XPlot GE NPlot) do begin
            read, XPlot,XFile,XPer
          endwhile
        endelse
                
        Clim6190 = [-999.0,-999.0,-999.0,-999.0]
        ClimFull = [-999.0,-999.0,-999.0,-999.0]

        if (X1961 NE -999 AND X1990 NE -999) then begin
		Clipped = Data(XFile,X1961:X1990,XPer)
        	Valid = where(Clipped NE -999.0, Count)
        	if (Count GT 1) then Clim6190 = moment(Clipped(Valid))
        endif
        
        Clipped = Data(XFile,*,XPer)
        Valid = where(Clipped NE -999.0, Count)
        if (Count GT 1) then ClimFull = moment(Clipped(Valid))
        
        print, "  > The climatologies of all, 1961-90 are: ", ClimFull[0], Clim6190[0]
        print, "  > Enter the base value and color: "
        read, XBase,XColor
        LineSpec(XPlot,XFile,XPer,0) = 66     & LineSpec(XPlot,XFile,XPer,1) = XBase
        LineSpec(XPlot,XFile,XPer,2) = -999   & LineSpec(XPlot,XFile,XPer,3) = XColor
        
        if (QKeyN EQ 1) then KeyLabel(0,    XFile,XPer)=PerLabel(XFile,XPer)
        if (QKeyN EQ 2) then KeyLabel(XPlot,XFile,XPer)=PerLabel(XFile,XPer)
        
        DataNAN = Data(XFile,*,XPer) & Missing = where(DataNAN EQ -999.0, Count) 
        if (Count GT 0) then DataNAN(Missing) = !Values.F_NaN
        LineDataMin = min(DataNAN,max=LineDataMax,/nan)
        if (PlotSpec(XPlot,1,0) GT LineDataMin) then PlotSpec(XPlot,1,0) = LineDataMin
        if (PlotSpec(XPlot,1,1) LT LineDataMax) then PlotSpec(XPlot,1,1) = LineDataMax
  endif else if (XPlot GE 0 AND XPlot LT NPlot) then begin
        if (NFile EQ 1) then begin
          XFile=0 & XPer=-1
          print, "  > Select the time period (0-16) to plot: "
          while (XPer LT 0 OR XPer GT 16) do begin
            read, XPer
          endwhile
        endif else begin
          XPer=-1 & XFile=-1
          print, "  > Select the file and time period (0-16) to plot: "
          while (XPer LT 0 OR XPer GT 16 OR XFile LT 0 OR XFile GE NFile) do begin
            read, XFile,XPer
          endwhile
        endelse
        
        print, "  > Enter the symbol,style,thickness,color: "
        read, XSym,XStyle,XThick,XColor
        LineSpec(XPlot,XFile,XPer,0) = XSym   & LineSpec(XPlot,XFile,XPer,1) = XStyle
        LineSpec(XPlot,XFile,XPer,2) = XThick & LineSpec(XPlot,XFile,XPer,3) = XColor
        
        if (QKeyN EQ 1) then KeyLabel(0,    XFile,XPer)=PerLabel(XFile,XPer)
        if (QKeyN EQ 2) then KeyLabel(XPlot,XFile,XPer)=PerLabel(XFile,XPer)
        
        DataNAN = Data(XFile,*,XPer) & Missing = where(DataNAN EQ -999.0, Count) 
        if (Count GT 0) then DataNAN(Missing) = !Values.F_NaN
        LineDataMin = min(DataNAN,max=LineDataMax,/nan)
        if (PlotSpec(XPlot,1,0) GT LineDataMin) then PlotSpec(XPlot,1,0) = LineDataMin
        if (PlotSpec(XPlot,1,1) LT LineDataMax) then PlotSpec(XPlot,1,1) = LineDataMax
  endif

  print, "  > Select a plot (66=bar-plot,77=update,99=end):"
  read, XPlot  
endwhile

;***************************************
; KEY SPECS

if (QKeyN GT 0) then begin
  print, "  > ADJUST KEY LABELS."
  XPlot = 77
endif else begin
  XPlot = 99
endelse
  
while (XPlot NE 99) do begin
  if            (XPlot EQ 77) then begin
  	UpdatePlotTS,YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,0,Title
  endif else if (XPlot GE 0 AND XPlot LT NPlot) then begin
        XFile=-1 & XPer=-1 & print, "  > Select the file, period: "
        while (XFile LT 0 OR XFile GE NFile OR XPer LT 0 OR XPer GE NPer) do begin
          read, XFile, XPer
        endwhile
        
        print, "  > Enter the label ('omit' is OK): "
        read, Label
        GiveSymbol, Label
        
        if (Label EQ "omit") then begin
          KeyLabel(XPlot,XFile,XPer) = ""
        endif else begin
          KeyLabel(XPlot,XFile,XPer) = Label
        endelse
  endif

  print, "  > Select a key (77=update,99=end):"
  read, XPlot  
endwhile

;***************************************
; PLOT SPECS
; identify plot then details
;	XPlot (77=update,88=all,99=end)
;	XAxis,XSpec,Value  XSpec:0=min,1=max,2=ticks,3=extra-axis,4=grid(1=Y)
;		4 can be set to -0.03 to force outside-plot ticks

print, "  > ADJUST PLOT ATTRIBUTES 0=min,1=max,2=ticks,3=2nd,4=grid(1=Y)"

XPlot = 77
while (XPlot NE 99) do begin
  if            (XPlot EQ 77) then begin
;  	UpdatePlotTS,YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,0,Title
  	UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,0,1,Title
  endif else if (XPlot EQ 88) then begin
        XAxis=-1 & print, "  > Select the axis (0=X,1=Y), attribute, and value: "
        while (XAxis LT 0 OR XAxis GT 1) do begin
          read, XAxis, XAttrib, ValueFloat
        endwhile
        for XPlot = 0, NPlot-1 do begin
          PlotSpec(XPlot,XAxis,XAttrib) = ValueFloat
        endfor
  endif else if (XPlot GE 0 AND XPlot LT NPlot) then begin
        XAxis=-1 & print, "  > Select the axis (0=X,1=Y), attribute, and value: "
        while (XAxis LT 0 OR XAxis GT 1) do begin
          read, XAxis, XAttrib, ValueFloat
        endwhile
        PlotSpec(XPlot,XAxis,XAttrib) = ValueFloat
  endif

  print, "  > Select a plot (77=update,88=all,99=end):"
  read, XPlot  
endwhile

;***************************************
; DUMP TO .ps or .eps
; select file and dump

;PSPath = ""
;print, "  > Enter the filepath of the .ps file (<return> = no save): "
;read, PSPath
;if (strlen(PSPath) GT 0) then begin
;  Set_Plot, 'ps', /copy
;  device, filename=PSPath, bits_per_pixel=8, xsize=XPixels/20, ysize=YPixels/20, /Color
;  UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,1,1,Title
;  device, /close
;endif

SavePath = ""
print, "  > Enter the filepath of the .eps or .cgm file: "
read, SavePath
EPSbeg = strpos(SavePath,".eps")
CGMbeg = strpos(SavePath,".cgm")

if (EPSbeg ne -1) then begin
  print, "  > Plotting to .eps ..."
  Set_Plot, 'ps', /copy
  device, filename=SavePath, bits_per_pixel=8, xsize=XPixels/20, ysize=YPixels/20, /Color, /Encapsulated
  UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,1,1,Title
  device, /close
endif else if (CGMbeg ne -1) then begin
  print, "  > Plotting to .cgm ..."
  Set_Plot, 'cgm', /copy
  device, filename=SavePath
  UpdatePlotTS, YearAD,Data,PlotLabel,KeyLabel,PlotSpec,LineSpec,TopBarSpec,PlotCorners,KeyCorners,QKeyN,1,1,Title
  device, /close
endif else begin
  print, "  > Unsuitable file suffix. No plot."
endelse

set_plot, 'X'

;***************************************
; END MAIN LOOP

print, "  > Satisfied? (0=ends,1=cycle through options)"
read, QSatisfied

endwhile

ScreenPlot = !D.window
wdelete, ScreenPlot

end
