

FUNCTION eis_mapper_month_calendar, month, year, outdir=outdir

;+
; NAME:
;      EIS_MAPPER_MONTH_CALENDAR
;
; PURPOSE:
;      Creates a html table containing the days of a
;      month. Optionally, the days will be links to EIS Mapper html
;      files. 
;
; CATEGORY:
;      Hinode/EIS; quicklook.
;
; CALLING SEQUENCE:
;      Result = EIS_MAPPER_MONTH_CALENDAR( Month, Year )
;
; INPUTS:
;      Month:   An integer specifying month.
;      Year:    An integer specifying year.
;
; OUTPUTS:
;      A string array containing html commands defining a html
;      <table>. For each day in the table, the routine checks in the
;      directory $EIS_MAPPER/year to see if the EIS mapper file for
;      that day exists. If it does, then a link to the file is
;      inserted. 
;
; EXAMPLE:
;      IDL> eis_mapper_month_calendar, 2, 2016
;
; MODIFICATION HISTORY:
;      Ver.1, 15-Aug-2018, Peter Young
;      Ver.2, 10-Mar-2020, Peter Young
;        Added parameter check.
;-

IF n_params() LT 2 THEN BEGIN
  print,'Use:  IDL> text = eis_mapper_month_calendar( month, year )'
  return,''
ENDIF 


eis_mapper_dir=getenv('EIS_MAPPER')

IF n_elements(outdir) NE 0 THEN BEGIN
  chck=file_search(outdir,count=count)
  IF count EQ 0 THEN file_mkdir,outdir
ENDIF ELSE BEGIN 
  IF eis_mapper_dir EQ '' THEN BEGIN
    print,'% EIS_MAPPER_CALENDAR: the $EIS_MAPPER environment variable is not defined.'
    return,''
  ENDIF ELSE BEGIN
    outdir=eis_mapper_dir
  ENDELSE
ENDELSE 


days=[31,28,31,30,31,30,31,31,30,31,30,31]

IF leap_year(year) THEN days[1]=29

ndays=days[month-1]
nwks=ceil(ndays/7.)

output=['<table>', $
        '<tr><td colspan=7 align=center><b>', $
        get_month(month-1), $
        '</b></td></tr>']

FOR i=0,nwks-1 DO BEGIN
  output=[output,'<tr>']
  FOR j=0,6 DO BEGIN
    dd=i*7+j+1
    n_doy=doy(trim(dd)+'-'+get_month(month-1)+'-'+trim(year))
    link_dir=concat_dir(outdir,'html')
    link_dir=concat_dir(link_dir,trim(year))
    link_name='mapper_'+strpad(trim(n_doy),3,fill='0')+'.html'
    file_name=concat_dir(link_dir,link_name)
    chck=file_search(file_name,count=count)
    IF count EQ 0 THEN BEGIN
      IF dd LE ndays THEN output=[output, $
                                  '<td>'+strpad(trim(i*7+j+1),2,fill='0')+'</td>']
    ENDIF ELSE BEGIN 
      IF dd LE ndays THEN output=[output, $
                                  '<td><a href="'+link_name+'">'+strpad(trim(i*7+j+1),2,fill='0')+'</a></td>']
    ENDELSE 
  ENDFOR 
  output=[output,'</tr>']
ENDFOR

output=[output,'</table>']

return,output

END
