pro dbase2disk, time0, time1, infile=infile, $
    outdisk=outdisk, prefix=prefix, select=select, $
    monode=monode, drive=drive, tape=tape, verify=verify, debug=debug
;+
;   Name: dbase2disk
;
;   Purpose: copy files from MO to output disk (magnetic or MO)
;
;   Input Parameters:
;      time0 - dbase times of interest OR start times of ranges
;      time1 - (optional) stop time of ranges (dimension must equal time0)
;   
;   Optional Keyword Parameters:
;      infile - time vector or time ranges in Yohkoh string format
;               (may be used in place of time0 & time1)
;      outdisk - directory name for output - or, one of the following codes...
;                1:find mathching week directory 2:find matching month directory
;      prefix  - instrument prefix(s) for selection
;      select  - if set, menu selection of MO subset
;      monode  - if set, mo nodename (default is local machine)
;      drive   - if set, MO or Tape drive number (default=0)
;      tape    - if set, loop through Tapes, not MOs (not yet implemented)
;      verify  - if set, verify integrity of tranfered files
;      
;   Restrictions:
;      UNIX only (MO is ISAS only for now - can be extended to exabyte tape)
;
;   History:
;      1-Dec-1994 (SLF) - derived from go_mo etc...
;      3-Dec-1994 (SLF) - slightly more generic, call tim2dbase directly
;      5-Dec-1994 (SLF) - comment, verify output, more diagnostics in logfile
;-

; ---------------- identify output disk/path ------------------------
if not keyword_set(outdisk) then begin
   outdisk=''
   defdir=curdir()
   tbeep
   read,"Enter output directory (def=" + defdir + "): ",outdisk
   if outdisk eq '' then outdisk=defdir
endif
; --------------------------------------------------------------------

; --------------- MO stuff is ISAS/UNIX hardcoded --------------------
drive=keyword_set(drive)
if not keyword_set(monode) then monode=get_host(/short)
moname='/mo' + strtrim(drive,2)+'.' + monode
subdir='/yohkoh/*/'
; ------------------------------------------------------------------------

; --------- Call tim2dbase to convert times to dbase parameters -----------
message,/info,"Calling TIM2DBASE to get fileids, MO names etc..."
tim2dbase,time0, time1, infile=infile, fids=fids, mos=mos, weekid=weekid, $
   uweeks=uweeks, umos=umos, /hc

; ---------------- allow menu selection of mo subset -------------
if keyword_set(select) then begin
   moss=wmenu_sel(umos)
   if moss(0) eq -1 then begin
      message,/info,"Nothing selected, quitting..."
      return
   endif else umos=umos(moss)
endif 
umos=strtrim(umos,2)
; ---------------------------------------------------------------
if not keyword_set(prefix) then begin
   allpre=['ada','bda','hda','sfr','spr','wda']
   defss=lindgen(n_elements(allpre))
   tbeep
   message,/info,"No instrument prefix supplied - please select prefix(s)'
   ss=wmenu_sel(allpre)
   if ss(0) eq -1 then message,"Nothing selected, aborting..."
   prefix=allpre(ss)   
endif
; -----------------------------------------------------------------
resp=''
tbeep
prstr,["You will need the following MOs to accomplish this task...", $
        string(umos,format='(10(a5,2x))'),'']
read,"Enter <CR> to continue, anything else to quit: ",resp
if resp(0) ne '' then stop,"Aborting run on request..."

; ------------- define and open some log files ---------------------
logs=[['bad', "Problem files..."], $
      ['skip',"MOs skipped..."],   $
      ['copy',"Succesfully copied files..."]]

logdir=get_logenv('HOME')
logs(0,*)=concat_dir(logdir,'dbase2disk_' + logs(0,*))
for i=0,n_elements(logs(0,*))-1 do file_append,logs(0,i),[logs(1,i),''],/new
; --------------------------------------------------------------------

; ------------- loop through mos or tapes ---------------------------
for i=0,n_elements(umos)-1 do begin
   tbeep
;  ----------------- present user options menu ----------------------
   text=[">>> Load MO# " + umos(i) + " on " + monode + ", drive# " + strtrim(drive,2) + " and select option...","", $
          "    <CR>:  to continue",			$
          "      s : to skip this MO",			$
          "      d : to define new output directory",	$
          "      q : to quit program"]
   prstr,strjustify(text,/box)
   read,  " option >>> ",resp
   print
;  --------------------------------------------------------------------   
   case strlowcase(strmid(resp,0,1)) of
      'd': begin
         read,"Enter new output pathname: ",resp
         while not file_exist(resp) do begin
            yesnox,"Directory: " + resp + " does not exist; Create it?",ans,'Y'
            if ans then begin
               spawn,'mkdir -p ' + resp
               if not file_exist(resp) then message,/info,"Cannot create " + resp + ".. check protection"
            endif else input,"Enter new output pathame",resp,outdisk
         endwhile
         outdisk=resp         
      endcase
      'q': begin
          message,/info,"Exiting program on request..."
          prstr,"Status saved in logfiles...",logs(0,*)
          return
       endcase
       else:
   endcase

   if strupcase(resp(0)) eq 'S' then begin		; skip MO
      mess='Skipping MO# ' + umos(i)
      message,/info,mess
      file_append,logs(0,1),mess,/uniq
   endif else begin
      momount,monode,drive=drive			; mount the drive
      ss=where(mos eq umos(i),cnt)			; fileids on this side

      files=reform(str_perm(prefix,fids(ss)))		; all 'possible' files
      nfiles=n_elements(files)
;     --------- identify files which do not exist in YOhkoh archive --------
      prstr,["Checking Yohkoh archive data base for files...",'   ' + files]
      reqsizes=get_afile_size(files)
      bad=where(reqsizes eq 0,bcnt)
      good=where(reqsizes,gcnt)
;     --------------------------------------------------------------
      if bcnt eq nfiles then begin
         print,"None of the specified files exist in data base..." 
      endif else begin  
;        ------------------ some exist, so prepar to copy --------------
         if bcnt eq 0 then prstr,"All specified files exist..." else $
            prstr,["The following files do not exist in data base...",files(bcnt)]
         files=files(good)
         filesize=total(reqsizes(good))
;        --------- verify space exists on specified output disk -------------
         freespace=diskfree(outdisk)
         print,"Verifying free space..."
         if freespace(0) lt (float(filesize(0))/1e6)(0) then begin
            tbeep
            message,/info,"requested copy will overflow disk " + outdisk
            read,"Clear some space and <CR> to continue or 'Q' to quit...",resp
            if is_member(resp,['q'],/wc,/case_ignore) then stop,"Quitting on request
         endif
;        -------------------------------------------------------------------

;        ------------ check source for requested files which exist --------
         list=file_list(concat_dir(moname,subdir),files)
         if list(0) eq '' then begin
            message,/info,"None of the expected files were found - check MO#
            file_append,logs(0,0),["Expected files on " + umos(i) + " not found", files]
         endif else begin
;        -------------------------------------------------------------------

;           ------------ spawn copy commands ------------------------
            cpcmds='/bin/cp ' + list + ' ' + outdisk       
            prstr,"Spawning following copy commands..."
            for j=0,n_elements(cpcmds)-1 do begin
               print,'>>> ' + cpcmds(j)
               spawn,str2arr(cpcmds(j),' '),/noshell
            endfor
;           ----------------------------------------------------------

;           ------------- Verification of copied files ---------------
	    message,/info,"Verifying copied files..."
            yo_file_check,concat_dir(outdisk,files),badfiles, allgood=allgood,status=status
            if allgood then begin
               print,"All existing files copied succesfully" 
            endif else begin
               prstr,["Problem with the following output files...",badfiles]
               file_append,logs(0,0),["Problem with the following output files...",badfiles]
	    endelse
            good=where(status eq 0,gcnt)
            if gcnt gt 0 then $
               file_append,logs(0,2),files(good)
;           --------------------------------------------------------------
      endelse

      message,/info,"Dismounting disk..."	; dismount
      momount,monode,drive=drive,/umount
     endelse
   endelse
endfor						; next side/tape till done

return
end


