	PRO mk_cd, dpath, flist=flist, select=select, ydb=ydb, sfd=sfd, $
		arcweek=arcweek, dupweek=dupweek, dest=dest, premaster=premaster, $
		nopremaster=nopremaster, nomaster=nomaster, noexecute=noexecute, $
		nolog=nolog, weekid=weekid, cdpath=cdpath, mkrootdir=mkrootdir
;		nobatch=nobatch		;to add later
;	----------------------------------------------------------------
;+							24-May-95
;	NAME: mk_cd
;
;	PURPOSE: Make a CD from data found in path "dpath".  Default
;		is for making CD's from general/personal data sets.
;		Use the /arcweek switch for making normal weely Yohkoh 
;		archive discs.  Use the /ydb switch to archive sfd files
;		and other weekly log files.
;
;	Parameters:
;		dpath		Input data path(s) (otherwise default dir)
;		flist		list of files to archive to CD using "/gen"
;		select		switch to allow interactive selection of
;				files to premaster.
;		ydb		to make CD archive from any of the
;				Yohkoh databases, e.g. sfd, sfm, ...
;		sfd		make CD archive f. an sfd db, same as ydb option
;		arcweek		to make a Yohkoh-Archive week CD
;		weekid		user specified week to archive 
;		dupweek		switch to allow making duplicate copies
;				of premastered data.
;		dest		destination for CD, self (default), UH,
;				SU, UCB, KH, UM, LPARL, NSSDC
;		premaster	restart from premaster stage
;		nopremaster	do not premaster or master data
;		nomaster	do not master data
;		noexec		do not execute script to make CD
;		nolog		do not log CD making
;		cdpath		list of root-level CD directories.  The
;				"dpath" directories are appended to
;				these directories. The number of
;				elements in dpath must equal number of 
;				elements in cdpath.
;		mkrootdir	Use the "archdir" var to make a root level
;				directory on the CD
;		
;	History:	written, GAL, 24-May-95
;		28-Nov-95, GAL, modified chmod command to -R a+wX/cdr_base/*
;			from -R a+wxX /cdr_base/*.
;		18-Mar-95, GAL, modified chmod command again.
;		 1-Apr-96, GAL, added cdpath and muilt path CD making.
;		2-Aug-96, GAL, yet another change to chmod now a+rwX/cdr_base
;		27-Sep-96, GAL, make NO root level dir. the default for
;			standard Yohkoh-Archive CDs.  Use the /mkrootdir
;			switch to make a CD with files in that dir.
;		29-Oct-96, GAL, bug fix to 'gen' or default mode.
;		
;-
;	---------------------------------------------------------------

;	---------------------------------------------------------------
;	setup constants, binary vars. and parameters
;	---------------------------------------------------------------
	cdmax = 677			; small pad for ymtrans.tbl files
					; actual capacity is 680Mb
	select = Keyword_set(select)	; setup binary vars.
	sfd    = Keyword_set(sfd)
	ydb     = Keyword_set(ydb)	
	arcweek   = Keyword_set(arcweek)
	dupweek= Keyword_set(dupweek)
;	dest   = Keyword_set(dest)	not a binary  keyword
	premaster   = Keyword_set(premaster)
	nopremaster = Keyword_set(nopremaster)
	nomaster    = Keyword_set(nomaster)
	noexecute = Keyword_set(noexecute)
	nolog  = Keyword_set(nolog)
	mkrootdir = Keyword_set(mkrootdir)

	mv_cp_cmd = 'mv '		; normal mv/cp command 
	if (sfd) then ydb = 1
	if (premaster) then dupweek = 1	; do not re-stage data
	if (nopremaster) then nomaster = 1
	if ( (not arcweek) AND (not ydb) ) then begin
	  gen = 1			; general/personal use CD making
	  noexecute = 1			; do this interactive
	endif else gen = 0
	if (dupweek) then dpath = '/cdr_base/'	; input path 
	mvcmd = ''			; init dir-tree move command	

;	Get Host, user, dir info:
	host = get_host(/short)		; get host
	user = getenv('USER')		; get user
	cd, current=defdir		; get current and default dir
	
;	--------------------------------------------------------------
;	Setup logging parameters:
;	--------------------------------------------------------------
	if (arcweek OR dupweek) then begin
	  logfn = '/ydb/cdcopy/'+host+'_week.log'
;DEBUG	  logfn = '/usr/people/linford/soft/'+host+'_week.log'
	endif
	if (ydb) then begin
	  logfn = '/ydb/cdcopy/'+host+'_ydb.log'
;DEBUG	  logfn = '/usr/people/linford/soft/cd/sfd/'+host+'_ydb.log'	
	endif
	if (n_elements(logfn) eq 0) then begin	; general use logging
	  if (not nolog) then begin
	    logfn = defdir+'/'+host+'.cd_log'
	    print, 'Your CD making will be logged to file: ', logfn
	    ans = 'y'
	    input, 'Continue with this log file?', ans, ans
	    if (strupcase(ans) ne 'Y') then begin
	      nlogfn = ''
	      input, 'Enter new path and log filename:', nlogfn, nlogfn
	      if (nlogfn ne '') then begin
		logfn = nlogfn
	      endif else begin
		nolog = 1		; NO LOGGING
	      endelse
	    endif
	  endif
	endif

;	Script file
	my_cd = defdir+'/my_cd'		; path to script

;	------------------------------------------------------------
;	Prepare Staged Data
;	------------------------------------------------------------
	if (not dupweek) then begin	; prepare staged data
	  status = 0
	  if (arcweek) then begin
;stop,'stop before prep_week'
	    status = prep_week(dpath, cdmax, archdir, mvfiles, logdiscna, $
			dest=dest, rdtap_script=rdtap_script, $
			weekid=weekid)
	    if (rdtap_script(0) eq '') then mv_cp_cmd = 'cp '	; data staged
;stop,'stop after... mvfiles...'
					; status=0 is failure
	  endif

	  if (ydb) then begin
	    status = prep_dat(dpath, cdmax, archdir, mvfiles, logdiscna, $
			dest=dest, select=select)

	  endif

	  if (gen) then begin		; general use mode
	    if (keyword_set(cdpath)) then begin	; check for missing /
	      for i=0, n_elements(cdpath)-1 do begin
		slashck = strpos(cdpath(i),'/',0)
		if (slashck ne 0) then cdpath(i) = '/'+cdpath(i)
	      endfor
	      createdirs = cdpath(uniq(cdpath, sort(cdpath)))	; unique list
	    endif
	    status = prep_gendat(dpath, flist=flist, cdmax, archdir, mvfiles, $
		mvcmd, logdiscna, dest=dest, select=select, cdpath=cdpath)
	  endif

	  if (not status) then begin	; failed to staged data
	    print, 'Failed to Prepare Staged Data.'
	    print, 'Return without building script.'
	    return
	  endif

	  disclab = strmid(logdiscna, 0, 14)	; make the disc label
						; from logging label
	  nfiles = n_elements(mvfiles)	; number of files

;	  ------------------------------------------------------------
;	  Build Script and Update Volume.inf file
;	  ------------------------------------------------------------

;	  Init. Script and Clean /cdr_base staging area:
	  iscript = ['#!/usr/bin/csh -f','umask 000']	; remove user protection
	  if (arcweek) then begin
	    if (rdtap_script(0) eq '') then begin	; data staged
	      script = [iscript,'rm -fr /cdr_base/*']
	    endif else begin  
	      script = [iscript, rdtap_script]
	      script = [script,'rm -fr /cdr_base/*']
	    endelse
	  endif else begin
	    script = [iscript,'rm -fr /cdr_base/*']	; init script w/rm files
	  endelse

;	  create root level directory, if requested:
	  if (not mkrootdir) then begin
	    archdir = '' 			; null out directory name
	  endif

	  if (archdir ne '') then begin
	    cdrd= '/cdr_base/'+archdir		; CDR directory
	    cdrm= '/cdr_base/'+archdir+'/.'	; CDR move path
	    mkd = 'mkdir /cdr_base/'+archdir
	    chm = 'chmod 777 '+cdrd
	    script = [script, mkd]
	    script = [script, chm]
	  endif else begin
	    cdrd = '/cdr_base'			; default CDR dir.
	    cdrm = '/cdr_base/.'		; CDR move path
	  endelse

;	  move files
	  chmodcmd = 'chmod -R a+rwX /cdr_base/*' 	; may have to use 774
	  if (mvfiles(0) eq '') then begin	; gen/mv dir-tree mode
	    if (n_elements(createdirs) ne 0) then begin	; create dirs
	      for i=0, n_elements(createdirs)-1 do begin
		script = [script, 'mkdir -p /cdr_base'+createdirs(i)]
		script = [script, 'chmod 777 /cdr_base'+createdirs(i)]
	      endfor
	    endif
  	    script = [script, mvcmd]
	    script = [script, chmodcmd]
	  endif else begin			; standard single dir mode
	    for i=0, nfiles-1 do begin
	      script = [script, mv_cp_cmd+mvfiles(i)+' '+cdrm]
	    endfor
	    script = [script, chmodcmd]
	  endelse

;	  THIS WAS MOVE TO CALLS TO SPECIFIC TYPES OF ARCHIVES
;	  Update volume.inf file
;	  if (arcweek) then volfn = '/sxt8data0/cdr_week/volume.inf'
;	  if (ydb) then volfn =  '/sxt8data0/cdr_ydb/volume.inf'
;	  if (gen) then volfn =  '/sxt8data0/cdr_gen/volume.inf'
;	  text = rd_tfile(volfn)	; read the volume file
;
;	  if (sfd) then begin
;	    voln = strmid(text(4), 15,1)            ; init vol. number
;	    yr = strmid(text(4),9,2)                ; init yr.
;
;	    disclab = 'sfd'+yr+volnams(voln-1)+'   '+'19'+yr+' vol. '+voln
;	    print, 'Current disc label: ', disclab
;	    print, 'Volume.inf: Current disc name: ', text(4)
;	    ans = 'y'
;	    input, 'Update this name?', ans, ans
;	    if (ans eq 'y') then begin
;  	      yr = strmid(text(4),9,2)
; 	      input, 'Update the Year?', yr, yr
; 	      stemp = text(4)
;  	      strput, stemp,yr,9
;  	      voln = strmid(text(4), 15,1)
;  	      input, 'Update the vol number', voln, voln
;  	      strput, stemp,voln,15
;  	      text(4) = stemp               ;update with changes;
;	    endif
;	    file_append, volfn, text, /newfile      ;write the new volume.inf               	    
;	  endif
;
;	  disclab = 'sfd'+yr+volnams(voln-1)+'   '+'19'+yr+' vol. '+voln


;	  Premaster command:
;		NOTE: I WANT TO GIVE USERS OPTIONS TO CHANGE THESE SWITCHES:
	  if (not nopremaster) then begin
	    if (arcweek) then begin
	      if (rdtap_script(0) ne '') then begin
	        premas1 = 'mt -f /dev/rmt5h rewind'
	        script = [script, premas1]
	      endif
	    endif
	    if (ydb) then $
  	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_ydb'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
	    if (arcweek) then $
	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_week'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
	    if (gen) then $
	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_gen'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
  	    script = [script, premas]
	  endif
	ENDIF ELSE BEGIN	; if (not dupweek) ELSE (it is a dupweek)

	  prt_flst, dpath, cdmax, logdiscna, dest=dest, ydb=ydb, $
			arcweek=arcweek, gen=gen
	  disclab = strmid(logdiscna, 0, 18)	; make the disc label
						; from logging label
	ENDELSE

;	Premastering commands (start from premaster stage):
	if (premaster) then begin	    
	    premas1 = 'mt -f /dev/rmt5h rewind' 
            if (n_elements(script) eq 0) then begin
	      script = premas1			; init script from premastering
	    endif else script = [script, premas1]
	    if (ydb) then $
  	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_ydb'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
	    if (arcweek) then $
	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_week'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
	    if (gen) then $
	      premas = '/ymi_links/makedisc -R -2 -b8 -g /sxt8data0/cdr_gen'+ $
		' /cdr_base YMTRANS.TBL /dev/rmt5h 680'
  	    script = [script, premas]
	endif

;	Mastering commands:
	if (not nomaster) then begin
	  premasck1 = '/usr/bin/echo -n "\n\n\nContinue to cut disc? [y] "'
	  premasck2 = 'set ans = $<'
	  premasck3 = 'if ($ans == y || $ans == "") then'
	  masck1  = 'nohup /ys/gen/script/idl_batch /usr/people/linford/soft/cd/sfd/connectio ~/ImkCD &' 	
	  masck2  = '/usr/bin/echo "\n\n\t\t>>>>> Please Note That <<<<<<<"'
	  masck3  = '/usr/bin/echo "\n\nThis script has been paused for 180sec while a connection "'
	  masck4  = '/usr/bin/echo "is made to the serial port on the CD mastering equipment for"'
	  masck5  = '/usr/bin/echo "error checking."'
	  masck6  = 'sleep 180'
	  mas1 = 'mt -f /dev/rmt5h rewind'
  	  mas2 = 'mt -f /dev/rmt5h fsf'
	  posmas1 = '/usr/bin/echo "\n\nMastering has started and should complete in about 1/2 hour."'
	  posmas2 = '/usr/bin/echo "\nPlease, remember to remove your completed CD from the Phillips."'
	  premasck4 = 'endif'
	  if (n_elements(script) eq 0) then begin	; mastering only
	    script = masck1
	    script = [script, masck2]
	    script = [script, masck3]
	    script = [script, masck4]
	    script = [script, masck5]
	    script = [script, masck6]
	    script = [script, mas1]
	    script = [script, mas2]
	    script = [script, posmas1]
	    script = [script, posmas2]
	  endif else begin				; premas & master
	    if (GEN) then begin				; user cks GENs
	      script = [script, premasck1]
	      script = [script, premasck2]
	      script = [script, premasck3]
	    endif
	    script = [script, masck1]
	    script = [script, masck2]
	    script = [script, masck3]
	    script = [script, masck4]
	    script = [script, masck5]
	    script = [script, masck6]
	    script = [script, mas1]
	    script = [script, mas2]
	    script = [script, posmas1]
	    script = [script, posmas2]
	    if (GEN) then begin
	      script = [script, premasck4]
	    endif
	  endelse

; 	  Mail init. notices:
	  mbody = '/ydb/cdcopy/cd_mas_start'
;  	  mbody = '/usr/people/linford/soft/cd/sfd/cd_mas_start' ; DEBUG
  	  msub  = 'Mastering Started: '+disclab
  	  users0  = getenv('MAIL_MK_CD')+','+user       ; list of CD makers
	;  users0 = user
  	  maicmd = 'Mail -s "'+msub+'" '+ users0 + ' < ' + mbody
	  script = [script, maicmd]
	endif
	
;	Write script and make it exec:
	file_append, my_cd, script, /newfile

	modcmd = 'chmod 777 '+my_cd
	modcmd = str2arr(modcmd, del=' ')
	spawn, modcmd, /noshell

;	-------------------------------------------------------------
;	Prompt user with name of Disc and hold for Inserting Media
;	-------------------------------------------------------------
	print, '   '
	print, 'Your NEW CD DISC label should read:
	print, '------------------------------------------------------------------'
	print, 'New Disc label: ', disclab
	print, '------------------------------------------------------------------'
	print, '   '
;	print, '***** Monitor the CD making process by issuing the command ****'
;	print, '**** below in a spare window and watch for "Write complete" ***'
;	print, '    '
;	print, '                /ymi_links/connect /dev/tty00'
;	print, '   '
	ans = 'y'
	print, '***** Place a Blank CD in the Recorder ******'
	input, 'Ready to continue with Blank CD in the Recorder?', ans, ans
	if (strupcase(ans) ne 'Y') then begin
          print, 'Returning without executing script'
          return
	endif	

	if (not noexecute) then begin
;         execmd = my_cd                 		; run the script
;         execmd = str2arr(execmd, del=' ')       	; most be string array
;         spawn, execmd, out, /noshell            	; run the script
;         print, 'Debug: dump execmd results: ', out

          execmd = 'nohup '+my_cd+' &'   		; run in the background
          spawn, execmd
	endif
	if ( GEN ) then begin 
	  print, '   '
	  print, '******* SPECIAL INSTRUCTIONS FOR MAKING GENERAL CDs *******'
	  print, '***** To make your Backup CD execute the script my_cd *****'
	  print, '   '
	  print, '***** Watch for the completion of the PRE-MASTERING   *****'
	  print, '***** Phase, which gives information on the percent   *****'
	  print, '***** of pre-mastering completed and the following:   *****'
	  print, '***** "Finished dumping CD-ROM image"                 *****'
	  print, '***** If you do not see this status message there     *****'
	  print, '*****                   was                           *****'
	  print, '***** pre-mastering error, do not proceed further.    *****'
	  print, ' '
	endif

	if (not nolog) then begin
          logstat = findfile(logfn)
          if (logstat(0) eq '') then begin        ; first log entry
            openw, loglun, logfn, /get_lun
          endif else begin
            openu, loglun, logfn, /get_lun, /append
          endelse
	  if (arcweek OR dupweek) then begin
	    st = strmid(!stime,0,17)
;		dummy example of how it should look:
;		use derived weekid to get xbd file and use tape name
;		from header, then "st", "dest", host.
;	    logstr = '95_13a.01-1.210 | 24-May-1995 09:22 | NSSDC | sxt8 '
		logstr = logdiscna	; use string from staging program
;		update with dest.
	  endif
	  if (ydb) then begin
;            flis = arr2str(fillst,del=',')
            st = strmid(!stime,0,17)
;           logstr = 'sfd'+yr+volnams(voln-1)+'  Vol. '+strtrim(voln,2)+' | '+st+' | '+flis
	    logstr = logdiscna		; use name from prep_dat.
	  endif
	  if (gen) then begin
;	    st = strmid(!stime,0,17)
;	    print, 'logging for gen not done'
	    logstr = logdiscna 		; use name from prep_gendat
	  endif

          printf, loglun, logstr
          free_lun, loglun
	  modcmd = 'chmod 777 '+logfn
	  modcmd = str2arr(modcmd, del=' ')
	  spawn, modcmd, /noshell
	endif

	print, '------------------------------------------------------------------'
	print, 'New Disc label: ', disclab
	print, '------------------------------------------------------------------'


	END
