FUNCTION GET_CACHE, j, flist, optid, ALL=all
;+
; Project     : SOHO - LASCO
;                   
; Name        : GET_CACHE
;               
; Purpose     : Implements caching of files in /tmp/idlpidxx. This speeds up processes which read 
;		many files from the jukebox by cutting down on CD mounts.
;               
; Use         : IDL> filename = GET_CACHE(j, list_of_filenames, pid)
;    
; Inputs      : j	INT	A subscript of flist
;		flist	STRARR	A list of filenames
;               
; Outputs     : filename	STR	filename in /tmp corresponding to flist[j]
;		idlpid		STR	output of getidlpid.pro
;		optid		STR	Optional additional identifier if more than one list
;					is being used.
;                             
; Keywords    :  /ALL		Retrieve all files in list
;
; Explanation : Checks to see if file i in flist is in /tmp. If not, copies flist[j:j+25] 
;		(or end of flist) to /tmp, and returns '/tmp/filename.fts' as the filename, 
;		which then is used as input to readfits or whatever.
;               
; Calls       : BREAK_FILE, SPAWN
;
; Category    : Data_Handling, I_O
;               
; Prev. Hist. : None.
;
; Written     : Nathan Rich, NRL/Interferometrics, 2002/01/07.
;               
; Modified    : 
;	02.05.23, nbr - Use IDLPID to create subdir in /tmp; add IDL_SESSION common block
;	02.05.31, nbr - Add optid
;
;
;	10/02/02, @(#)get_cache.pro	1.4 LASCO IDL LIBRARY
;-            

;______________________________________________________________________________
;

COMMON IDL_SESSION, pid
 
filename0=flist[j]
break_file,filename0,bflog,dir,fname,ext
IF datatype(pid) NE 'STR' THEN pid = getidlpid()
IF N_PARAMS() GT 2 THEN sfx = optid ELSE sfx=''
pidir = '/tmp/idl'+pid+sfx
filename= pidir +'/'+fname+ext

IF file_stat(filename,/size) LT 131000 THEN BEGIN
; If filename is nonexistent or smaller than equivalent of 256x256 image....
	cmd = '/bin/rm -fr '+pidir+'/*.fts'
	print,cmd
	spawn, cmd,/SH
	n=n_elements(flist)
	i0=where(flist EQ filename0,nii)
	i0=i0[0]
	IF keyword_set(ALL) THEN in = n-1 ELSE in = (i0+24) < (n-1)
	IF file_exist(pidir) LT 1 THEN BEGIN
		print,'mkdir '+pidir
		spawn,'mkdir '+pidir
	ENDIF
	FOR i=i0,in DO BEGIN
		cmd='cp '+flist[i]+' '+pidir
		print,cmd
		spawn,cmd,/SH
	ENDFOR
ENDIF 


return, filename

END
