;CP_get_times, Directory_file, indir
;
;INPUTS:
;	Directory_file		the file containing the names of all the 
;				fits files for a given date
;	indir			the directory where the .fits files are stored
;	
;
;

pro get_times, Directory_file=Directory_file, Readdir=Readdir, Writedir=Writedir

;Time will be coded as 2005*1000+Day_Number+hr/24+min/60+second/3600
year_offset=double(2005000)
time_gap=0.00012
num_of_telescope_shifts=0

;set directory path delimiter
    if (!version.os_family eq 'unix') then begin
       delim='/'
    endif else begin
       delim='\'
    endelse

;Defaults for keywords if not entered at command line
if (not keyword_set(Readdir)) then Readdir='/a/pippin01/Volumes/u08/lsst/CPcampaign/SOAR/2005-05-12/ShackHartman/Raw'
if (not keyword_set(Writedir)) then Writedir='/a/pippin01/Volumes/u08/lsst/CPanalysis/2005-05-12/ShackHartman'
if (not keyword_set(Directory_file)) then Directory_file=Writedir+delim+'Directory_files.txt'
                                                                               
                                                                                
;The files are in Writedir are listed in the file Directory_files.txt
readcol,Directory_file,Files,format='a'
num_of_files=N_elements(Files)
time_array=dblarr(num_of_files)
uttime_array=strarr(num_of_files)

;After organizing them by time, they will be written to Sorted_Directory_files.txt
openw,1,Writedir+Delim+'Sorted_Directory_files.txt',/append




for i=0,num_of_files-1 do begin

	file_name=Readdir+delim+Files(i)
	fits_read,file_name,image,header,/header_only
	uttime=SXPAR(header,'DATE-OBS')
	time_with_year=double(DATE_CONV(uttime,'R'))
	time_wo_year=time_with_year-year_offset
	time_array(i)=time_wo_year
	uttime_array(i)=uttime

;If the lapse in time between two successive images is greater than 
;time_gap, the telescope pointing has probably changed

endfor

sort_index=sort(time_array)
time_array_sorted=time_array(sort_index)
files_sorted=Files(sort_index)
uttime_array=uttime_array(sort_index)

;If the lapse in time between two successive images is greater than
;time_gap, the telescope pointing has probably changed                         
for i=0,num_of_files-1 do begin

	 if (i gt 0) then begin
                if time_array_sorted(i)-time_array_sorted(i-1) gt time_gap then begin
                        gap=time_array_sorted(i)-time_array_sorted(i-1)
                        seconds_gap=gap*24*3600.
			printf,1,'----------------------------------------------------'
			printf,1,FORMAT='(%"%s\t\t\t%d%s")','Found a gap of',seconds_gap,' seconds'
			printf,1,''
                        num_of_telescope_shifts=num_of_telescope_shifts+1
                endif
        endif

	printf,1,FORMAT='(%"%s\t\t%s\t\t")',files_sorted(i),uttime_array(i)
                                                                                
endfor


close,1

stop

end

