pro file_dedupe, dir
;+
; Project     : STEREO
;
; Name        : file_dedupe
;
; Purpose     : generate a script to remove duplicate files
;
; Explanation : 
;
; Use         : file_dedupe,directory_name
;
; Example     : file_dedupe,'~/test/db'
;
; Inputs      : dir STRING  directory to scan
;
; Outputs     : file './rm.sh'
;
; Keywords    : 
;
; Calls       : break_file
;
; Category    : system, files, admin
;
; Prev. Hist. : None.
;
; MODIFICATION HISTORY:
; $Log: file_dedupe.pro,v $
; Revision 1.3  2010/12/09 22:57:04  nathan
; sort
;
; Revision 1.2  2009/06/04 20:10:50  secchia
; updates
;
; Revision 1.1  2009/06/04 18:20:06  nathan
; born
;
pause=2
print,'Searching ',dir
files=file_search(dir,'*')
help,files,pause
n=n_elements(files)

roots=strarr(n)

for i=0L,n-1 do begin
    IF chk_dir(files[i]) THEN print,string(i,'(i7)'),' ',files[i],' is a directory.' $
    ELSE BEGIN
    ; only do files not directories
	break_file,files[i],dl,dir,fn,ext
	IF ext NE '.gz' and ext NE '.zip' and ext NE '.Z' THEN $
	    roots[i]=fn+ext ELSE $
	    roots[i]=fn
    ENDELSE
endfor

srt=sort(roots)
files=files[srt]
uq=uniq(roots[srt])
; for each duplicated file...
nu=n_elements(uq)
ndups=n-nu
help,ndups
wait,2
e=0
openw,1,'rm.sh'
FOR i=0L,nu-1 DO BEGIN
    IF e NE uq[i] THEN BEGIN
    	dups=files[e:uq[i]] 
	nd=n_elements(dups)
	; delete files iff in lower directory, which is completely included
	; in the higher directory path
    	dlen=strlen(dups)
	slen=sort(dlen)
	help,nd
	wait,pause
	IF roots[srt[e]] NE '' THEN $
	; not directories
	for j=0,nd-2 do begin
	    ; always keep longest
	    filen=dups[slen[j]]
	    break_file,filen,dl,dir,fn,ext
	    isdup=0
	    for k=j+1,nd-1 do begin
	    	dirtest=strpos(dups[slen[k]],dir)
		if dirtest GE 0 THEN isdup=1
	    endfor
	    IF isdup THEN BEGIN
	    	print,filen
		printf,1,'/bin/rm '+filen
	    ENDIF
	endfor
    ENDIF
    e=uq[i]+1
ENDFOR
close,1

end
