#
# $Log: not supported by cvs2svn $
# Revision 1.12  2008/09/24 16:13:25  soliday
# Added APSFindPVDataFiles
#
# Revision 1.11  2002/07/18 20:23:59  soliday
# Added the ability to find dated files without the julian day in the name.
#
# Revision 1.10  2001/02/06 19:44:22  soliday
# Fixed some tcl warning messages found with procheck
#
# Revision 1.9  1999/02/08 22:48:11  borland
# Added APSFindYoungestFile.
#
# Revision 1.8  1999/02/08 22:43:20  borland
# Added APSReturnOldestFile.
#
# Revision 1.7  1997/01/24 16:53:45  borland
# Now allow blank rootname.
#
# Revision 1.6  1996/10/08 17:23:12  borland
# Now sorts return lists before returning them.
#
# Revision 1.5  1996/09/24 14:31:14  borland
# Added help routines.
#
# Revision 1.4  1996/07/15  19:40:27  borland
# No longer appending - to end of rootname.  Must be provided by caller
# as part of rootname if needed.
#
# Revision 1.3  1996/07/04  20:09:40  borland
# Added -suffix option.
#
# Revision 1.2  1996/06/11  17:29:23  borland
# Added APSFindMonthlyFilesBetweenDates.
#
# Revision 1.1  1996/02/22  21:57:53  borland
# First version committed.  A routine to find standard monitoring output files
# between a range of dates.
#

proc APSFindPVDataFilesHelp {} {
    return "Usage: APSFindPVDataFiles -ReadbackName <string> 
-StartTime <epochTime> -EndTime <epochTime> 
-startDateList <dateList> -endDateList <dateList> 
-SampleIntervals <list> \n
where <dateList> contains year and Julian day."
}

proc APSFindPVDataFiles {args} {
    set ReadbackName ""
    set StartTime [clock scan "Jan 01 00:00:00 1990"]
    set EndTime [clock seconds]
    set startDateList ""
    set endDateList ""
    set SampleIntervals "1 2 4 8 16 32 64 128 256"
    APSStrictParseArguments {ReadbackName StartTime EndTime SampleIntervals startDateList endDateList}

    if {[llength $startDateList]} {
        set StartTime [clock scan "[lindex $startDateList 2]/[lindex $startDateList 3]/[lindex $startDateList 0]"]
    }
    if {[llength $endDateList]} {
        set EndTime [clock scan "23:59:59 [lindex $endDateList 2]/[lindex $endDateList 3]/[lindex $endDateList 0]"]
    }
    
    set fileList ""
    set ReadbackName [join [split $ReadbackName / ] + ]
    set year [clock format $StartTime -format %Y]
    set month [clock format $StartTime -format %m]
    set endyear [clock format $EndTime -format %Y]
    set endmonth [clock format $EndTime -format %m]
    while {($year < $endyear) || (($year == $endyear) && ($month <= $endmonth))} {
        append fileList "[lsort [glob -nocomplain /home/helios/oagData/logging/Variable/[string toupper [string index ${ReadbackName} 0]]/${ReadbackName}/log-${year}-${month}.{gz,xz}]] "
        append fileList "[lsort [glob -nocomplain /home/helios/oagData/logging/\{[join $SampleIntervals ,]\}/${ReadbackName}/log-${year}-${month}.{gz,xz,????}]] "
        if {$month == 12} {
            set month 01
            incr year
        } else {
            scan $month %d month
            incr month
            set month [format %02d $month]
        }
    }
    return $fileList
}

proc APSFindFilesBetweenDatesHelp {} {
    return "Usage: APSFindFilesBetweenDates -rootname <string> 
-startDateList <dateList> -endDateList <dateList> \[-extensionList <list>\]
\[-suffix <string>\] \[-directory <string>\] \[-tailsOnly 1\] \[-filter <filter>\] \n
where <dateList> contains year and Julian day."
}


#
# Finds files between given dates, with defaults for sddsmonitor files
# for the data logging jobs.
#
proc APSFindFilesBetweenDates {args} {
    set rootname ""
    set suffix ""
    set directory "."
    set tailsOnly 0
    set startDateList {}
    set endDateList {}
    set extensionList {"" ".\[0-9\]\[0-9\]\[0-9\]\[0-9\]" ".gz" ".xz"}
    set filter "-???-????"
    set excludeList ""
    APSStrictParseArguments {rootname directory startDateList endDateList 
	extensionList tailsOnly suffix filter excludeList}
    if {[llength $startDateList]==0 || [llength $endDateList]==0} {
        return 0
    }
    set startYear [APSMakeFourDigitYear [lindex $startDateList 0]]
    set endYear   [APSMakeFourDigitYear [lindex $endDateList 0  ]]
    scan [lindex $startDateList 1] "%ld" startJDay
    scan [lindex $endDateList   1] "%ld" endJDay

    set fileList {}
    for {set year $startYear} {$year<=$endYear} {incr year} {
        if {$year!=$endYear} {
            set toYearEnd 1
            set jDayLimit [expr {365+([APSLeapYear $year]?1:0)}]
        } else {
            set toYearEnd 0
            set jDayLimit $endJDay
        }
        set yearList [glob -nocomplain $directory/${rootname}${year}${filter}${suffix}*]
        if {[llength $yearList]} {
            if {$startJDay==1 && $toYearEnd==1} {
                set fileList [concat $fileList $yearList]
            } else {
                set newList {}
                for {set jDay $startJDay} {$jDay<=$jDayLimit} {incr jDay} {
                    set jDay3 [format %03ld $jDay]
                    while {[llength $yearList]} {
			if {$filter == "-????"} {
			    set index [lsearch -glob $yearList $directory/${rootname}${year}-[clock format [expr round([exec timeconvert -breakdown=year=${year},julianDay=${jDay},hour=1])] -format "%m%d"]${suffix}*]
			} else {
			    set index [lsearch -glob $yearList $directory/${rootname}${year}-${jDay3}-????${suffix}*]
			}
                        if {$index==-1} break
                        set newName [lindex $yearList $index]
                        if {$tailsOnly} {
                            set newName [file tail $newName]
                        }
                        
                        if {[llength $extensionList]} {
                            set match 0
                            set extension [file extension $newName]
                            foreach extensionPattern $extensionList {
                                if {[string match $extensionPattern $extension]} {
                                    set match 1
                                    break
                                }
                            }
                        } else {
                            set match 1
                        }
                        if $match {
                            if [llength $excludeList] {
                                foreach opt $excludeList {
                                    if [regexp $opt $newName] {
                                        set match 0
                                        break
                                    }
                                }
                            }
                        }
                        if $match {
                            lappend newList $newName
                        }
                        set yearList [lreplace $yearList $index $index]
                    }
                }
                set fileList [concat $fileList $newList]
            }
        }
        set startJDay 1
    }
    
    return [lsort $fileList]
}

proc APSFindMonthlyFilesBetweenDatesHelp {} {
    return "Usage: APSFindMonthlyFilesBetweenDates -rootname <string> 
-startDateList <dateList> -endDateList <dateList> \[-extensionList <list>\]
\[-suffix <string>\] \[-directory <string>\] \[-tailsOnly 1\]\n
where <dateList> contains year and month."
}

proc APSFindMonthlyFilesBetweenDates {args} {
    set rootname ""
    set suffix ""
    set directory "."
    set tailsOnly 0
    set startDateList ""
    set endDateList ""
    set extensionList {"" ".gz" ".xz"}
    APSStrictParseArguments {rootname directory startDateList \
                               endDateList extensionList tailsOnly suffix}
    if {[llength $startDateList]==0 || [llength $endDateList]==0} {
        return 0
    }
    set startYear [APSMakeFourDigitYear [lindex $startDateList 0]]
    set endYear   [APSMakeFourDigitYear [lindex $endDateList 0  ]]
    scan [lindex $startDateList 1] "%ld" startMonth
    scan [lindex $endDateList   1] "%ld" endMonth

    set fileList {}
    for {set year $startYear} {$year<=$endYear} {incr year} {
        if {$year!=$endYear} {
            set toYearEnd 1
            set endMonthLimit 12
        } else {
            set toYearEnd 0
            set endMonthLimit $endMonth
        }
        if {$year!=$startYear} {
            set fromYearStart 1
            set startMonthLimit 1
        } else {
            set fromYearStart 0
            set startMonthLimit $startMonth
        }
        set yearList {}
        foreach extension $extensionList {
            eval lappend yearList [glob -nocomplain $directory/${rootname}${year}-\[0-9\]\[0-9\]${suffix}$extension]
        }
        if {[llength $yearList]} {
            if {$fromYearStart && $toYearEnd} {
                set fileList [concat $fileList $yearList]
            } else {
                set newList {}
                for {set month $startMonthLimit} {$month<=$endMonthLimit} {incr month} {
                    set monthLZ [format %02ld $month]
                    while {[llength $yearList]} {
                        set index [lsearch -glob $yearList $directory/${rootname}${year}-${monthLZ}${suffix}*]
                        if {$index==-1} break
                        set newName [lindex $yearList $index]
                        if {$tailsOnly} {
                            set newName [file tail $newName]
                        }
                        if {[llength $extensionList]} {
                            set match 0
                            set extension [file extension $newName]
                            foreach extensionPattern $extensionList {
                                if {[string match $extensionPattern $extension]} {
                                    set match 1
                                    break
                                }
                            }
                            if {$match} {
                                lappend newList $newName
                            }
                        } else {
                            lappend newList $newName
                        }
                        set yearList [lreplace $yearList $index $index]
                    }
                }
                set fileList [concat $fileList $newList]
            }
        }
    }
    return [lsort $fileList]
}

proc APSReturnOldestFileHelp {} {
    return "usage: APSReturnOldestFile -fileList <list>\n
Returns the name of the oldest file in the list."
}
    
proc APSReturnOldestFile {args} {
    set fileList ""
    APSStrictParseArguments {fileList}
    if {![llength $fileList]} {
        return ""
    }
    set oldestFile ""
    # The oldest file has the smallest modification time 
    set oldestTime [expr {2*[clock seconds]}]
    foreach filename $fileList {
        if {![file exists $filename]} continue
        set mtime [file mtime $filename]
        if {$mtime<$oldestTime} {
            set oldestFile $filename
            set oldestTime $mtime
        }
    }
    return $oldestFile
}

proc APSReturnYoungestFileHelp {} {
    return "usage: APSReturnYoungestFile -fileList <list>\n
Returns the name of the youngest file in the list."
}
    
proc APSReturnYoungestFile {args} {
    set fileList ""
    APSStrictParseArguments {fileList}
    if {![llength $fileList]} {
        return ""
    }
    set youngestFile ""
    # The youngest file has the largest modification time
    set youngestTime 0
    foreach filename $fileList {
        if {![file exists $filename]} continue
        set mtime [file mtime $filename]
        if {$mtime>$youngestTime} {
            set youngestFile $filename
            set youngestTime $mtime
        }
    }
    return $youngestFile
}

