pro mo_check, moname, monode, drive=drive, readchk=readchk, fidcheck=fidcheck, $
	badtot=badtot, summary=summary
;
;+
;   Name: mo_check
;
;   Purpose: verifiy MO integrity (all files included, proper size, readcheck)
;
;   Input Parameters:
;      monode - Node with MO driver (string), Example: 'flare15'
;      moname - Name of MO to check (string), Example: '109B'
;
;   Output Parameters:
;      badtot  - number of bad files on mo
;      summary - Text summary of MO status
; 
;   Optional Keyword Parameters:
;      drive   -  drive number (default is drive 0)
;      readchk - if set, read checks of all MO files are performed
;		 (via yo_file_check) - default is to confirm existance $ size
;
;   History:
;      1-Jul-1994 (SLF)
;      4-Jul-1994 (SLF) Made functional, add bad logs, etc.
;      6-Jul-1994 (slf) Version 2 log (only write bad files to 'bad' logs)
;			So, mochk_NNNX.02 has diagnostics
;			    mochk_bad.NNNX contains bad file list
;      7-Jul-1994 (slf) Use timegrid.pro to generate time grid 
;      8-Jul-1994 (slf) add output SUMMARY (text) and badtot (number bad)
;			trim fid array (sometimes took the extreme)
;     10-Jul-1994 (slf) Truncate summary file and output to minimize garbage
;			(full listing is maintained in 'mochk_bad.xxxN')  
;     14-Sep-1994 (slf) add ada to prefix list!
;      3-Oct-1995 (LS)  modified code to work with new output of momount.pro,
;			 which changed when it started using mo_mount
;-
; ----------------- mount the MO ----------------------
if n_elements(monode) eq 0 then monode=(str2arr(get_host(),'.')) (0)
driven=0
if keyword_set(drive) then driven=drive
message,/info,"momount," + monode + " , drive=" + strtrim(driven,2)
momount, monode, drive=drive, status=status
; 
; ------------ verify mount ------------------------
mname=strtrim(str2arr(status,' '),2)
which = where(strpos(mname,'/mo') eq 0,wcnt)
mount=''
if wcnt gt 0 then spawn,'ls ' + mname(which(0)),resp
if (size(resp))(0) eq 0 then begin
   message,/info,"Momount failure for node: " + monode + ", drive# " + strtrim(driven,2)
   message,/info,"Verify proper drive is loaded, and retry... returning,
   return
endif else begin
   avail=diskfree(mname(which(0)),mount=mount)
   message,/info,"MO Mounted OK, Name: " + mount + $
	" Available: " + strtrim(avail,2) + " Mbytes"
endelse
; -------------------------------------------------------------

; ------------- read the MO log file --------------------------
mdmdat=rd_modb(/all)
if not data_chk(mdmdat,/struct) then message,"Error reading MO data base file...
; ------------------------------------------------------------

; -------------------- Verify MO name ------------------------------
if n_elements(moname) eq 0 then begin
   tbeep
   message,/info,"You did not supply an MO name in your call..."
   moname=''
   read,"Enter 4 character MO Name, (<cr> to quit) :",moname
endif
if strlen(moname) ne 4 then begin
   message,/info,"No MO name given, exiting...
   return
endif
mon=strupcase(moname)
; ------------------------------------------------------------------

nrecs=n_elements(mdmdat)
sides=string(reform(mdmdat.st$side,1,nrecs))
; ----------- Find mdmdat record with matching mo name -------------
sname=string(mdmdat.mo_disk,format='(I3.3)') + sides

whichmo=where(sname eq mon,nss)
if nss eq 0 then begin
   message,/info,"No MO log record matches input moname: " + mon
   message,/info,"Exiting..."
   return
endif else begin
   messages="MO log match for MO: " + mon + " found in log record# + strtrim(whichmo,2)
endelse
; ------------------------------------------------------------------


; ------------------- ascii log file use unique version number ---------
ver=2
mochklog=$
 concat_dir('$DIR_SITE_MOLOGS','mochk_' + mon + string(ver,format='(".",i2.2)'))
; disabled following code to maintain versions....
;while file_exist(mochklog) do begin
;   ver=ver+1
;   mochklog=$
;    concat_dir('$DIR_SITE_MOLOGS','mochk_' + mon + string(ver,format='(".",i2.2)'))
;endwhile
; ------------------------------------------------------------------------
;
; ----------------- create log for -------------------------------
messages=["mo_check for MO " + mon + " run at " + !stime + " by " + get_user()]
message,/info,messages(0)
logit=1-keyword_set(fidcheck)
; ascii log file containing problem disks (format allows use in patching??)
mobadlog=concat_dir('$DIR_SITE_MOLOGS','mochk_bad.' + mon)
file_append,mobadlog, messages, /new
spawn,'chmod 666 ' + mobadlog
; -----------------------------------------------------------------

; Only get here with at least one log match.
logrec=mdmdat(whichmo)				; last one
fid0=string(logrec.ST$FIRST_FID)
fidn=string(logrec.ST$LAST_FID)
weekn=string(logrec.st$week)
fidcnt=logrec.nfid

file_append,mochklog,/new,messages
moinst=['ada','sfr','spr','hda','wda','bda']
; for each subdirectory (week) on this MO, 
toplev=concat_dir(mount,'yohkoh')
badtot=0
for i=0,n_elements(logrec)-1 do begin
   messages="Week: " + weekn(i) + ", First FID: " + fid0(i) + $
	" , Last FID: " + fidn(i)
   message,/info,messages
   file_append,mochklog,messages
;  generate a FID array with all posibile fids between first and last
   tim0=fmt_tim(fid2ex(fid0(i)))
   timn=fmt_tim(fid2ex(fidn(i)))
   grid=timegrid(tim0,timn,/hour)		; 1 hour seperation
   tim2orbit,grid,fid=fid
   fid=[fid0(i),fid,fidn(i)]		; make sure extremes are included
   fid=fid(uniq(fid,sort(fid)))		; uniq set 
   fidss=where(fid ge fid0(i) and fid le fidn(i))
   fid=fid(fidss)
   allfiles=str_perm(moinst,fid)	; vector of all possible file names
   esizes=get_afile_size(allfiles)	; check xbd data base sizes via GAL.
   somedata=where(esizes,escnt)
   if escnt eq 0 then begin
      message,/info,"No data in all files???" 	; Should never happen, but...
   endif else begin
      esizes=esizes(somedata)			; expected sizes (via XBD)
      allfiles=allfiles(somedata) 
      mofiles=concat_dir(concat_dir(toplev,weekn(i)),allfiles)	; mo names
      mosizes=file_stat(mofiles,/size)				; mo sizes
      bad=where(mosizes ne esizes,bcnt)		; mo size NE XBD size -> problem
      if bcnt gt 0 then begin
         badtot=badtot+bcnt
         shortlist=mofiles(bad)
         if bcnt gt 5 then shortlist=$
	    [ mofiles(bad(0:4)),"",	$
	    '[..... list truncated; full list in ' + mobadlog + ' ]',""]
         messages=[strtrim(bcnt,2) + " files missing or have unexpected sizes...",shortlist]
         message,/info,messages(0)
         if logit then begin
            file_append,mochklog,messages
            file_append,mobadlog, $
	       ["MO " + mon + " " + messages(0), mofiles(bad)]
         endif
      endif else begin
         messages="All files for week " + weekn(i) + " exist and are expected size"
	 message,/info,messages
         file_append,mochklog,messages
      endelse
   if keyword_set(fidcheck) then stop,"fidcheck...."
   endelse
endfor
mess= ["mo_check for MO: " + mon + " completed at: " + !stime,  $
   "Total Bad/Missing Files: " + strtrim(badtot,2)]
file_append,mobadlog,mess
message,/info,mess(0)
message,/info,'>>>>>>  ' + mess(1) + '  <<<<<<'


summary=[rd_tfile(mochklog),'',mess(0),'','>>>>>>  ' + mess(1) + '  <<<<<<']

return
end

