#!/bin/sh
# \
exec oagtclsh "$0" "$@"
# $Log: not supported by cvs2svn $
# Revision 1.42  2011/08/31 13:53:28  soliday
# Fixed a bug with the tech note year for revisions sent to ICMS. Also
# added some debugging statements that will email me when reports are submitted.
#
# Revision 1.41  2011/08/23 16:31:12  soliday
# Added the ability to submit tech notes directly to ICMS from this script.
#
# Revision 1.40  2011/06/07 13:15:01  flood
# Changed web path from Operations_Analysis to Accelerator_Operations_Physics
#
# Revision 1.39  2010/05/25 19:31:04  shang
# it now accepts special characters for example comma in the title.
#
# Revision 1.38  2009/03/25 21:20:12  borland
# No longer sends email for revisions.
#
# Revision 1.37  2009/03/23 16:19:10  shang
# fixed a bug in submitting new report that it complained about year not provided, which should not for submitting new report.
#
# Revision 1.36  2009/03/19 20:45:37  shang
# added checking the existence of report file and fixed a problem that it could not submit note starting with "tnote"
#
# Revision 1.35  2008/11/24 16:15:43  soliday
# Added a missing close bracket
#
# Revision 1.34  2008/11/17 18:33:17  flood
# Added search widget
#
# Revision 1.33  2008/11/17 18:03:47  borland
# Added update option (to regenerate main page).
# Added sorting by numerical date (NDate).
#
# Revision 1.32  2008/11/14 17:21:39  borland
# Added automatic notification emails.
#
# Revision 1.31  2008/11/14 16:40:07  borland
# Updated to accomodate merging of AP group notes.
#
# Revision 1.30  2008/09/29 14:54:15  shang
# addec checking if generating note file exists before copy report to it to avoid overwriting existing notes.
#
# Revision 1.29  2008/09/29 14:42:38  shang
# fixed a bug in getting the note number when submitting the new tech note, because the files were not collected correctly with missing path name.
#
# Revision 1.28  2008/09/15 18:33:49  shang
# fixed a bug that it could not find the file if the full pathname was not given.
#
# Revision 1.27  2008/08/20 20:42:39  borland
# Should fix bug in making the link name with no .pdf extension.
#
# Revision 1.26  2008/08/19 20:48:48  shang
# modifed to use tnote<year>-<number>.pdf for the note file name which is a symbolic link to the actual note file.
#
# Revision 1.25  2008/05/20 19:56:45  shang
# changed bach to directly write to oagTechnicalReports.html, but added a empty line right
# before the "Copyright Notice" line, as other reports html files. Tested with a revision report, it seemed working -- the browser updated the report page afte refresh button is pressed.
#
# Revision 1.24  2008/05/19 18:25:01  shang
# now it writes the oag technical reports into a temporary file and then copies the temporary file into oagTechnicalReports.html.
#
# Revision 1.23  2008/05/13 22:27:56  shang
# replaced oagTechnicalReports.shtml by oagTechnicalReport.html to see if the latter one can
# be recongnized by the web browser after it is being updated.
#
# Revision 1.22  2008/05/01 18:03:08  shang
# removed the table entry for year=0.
#
# Revision 1.21  2008/05/01 17:59:22  shang
# modified the seach button.
#
# Revision 1.20  2008/04/30 12:24:07  flood
# Added search option to category page
#
# Revision 1.19  2008/04/29 21:49:54  shang
# added missing "</body></html>" to the end of oagTechnicalReports.shtml, this should fix the problem that it was not recognized even though it was updated.
#
# Revision 1.18  2007/11/05 19:21:26  shang
# added checking the user and workstation and exit if the user is not oag or workstation is not challenger
#
# Revision 1.17  2007/02/12 16:22:34  shang
# fixed problem in checking revision number (should be !$revision)
#
# Revision 1.16  2007/02/12 16:15:43  shang
# fixed a bug in checking the revision and notenumber
#
# Revision 1.15  2007/02/06 20:21:21  shang
# added checking if the title of new report already exists in old report and fixed the problem of submitting
# revised report.
#
# Revision 1.14  2006/05/05 20:48:31  soliday
# Updated to use the new location for the APSOnly web pages.
#
# Revision 1.13  2006/04/03 16:39:47  soliday
# Updated to use the new Operations & Analysis web site.
#
# Revision 1.12  2005/09/30 14:24:11  shang
# modified to accept categories with full name in addition to abbreviates
#
# Revision 1.11  2005/06/09 19:32:24  shang
# made it possible to submit an old dated note with new note number
#
# Revision 1.10  2005/06/09 18:33:27  shang
# fixed misspelling error
#
# Revision 1.9  2005/03/17 21:56:02  shang
# added inputDir argument to UpdateOAGReportPage proc to write the oag report
# homepage file into given directory.
#
# Revision 1.8  2005/03/17 21:27:11  shang
# fixed a bug in regexp expression with special characters
#
# Revision 1.7  2005/03/15 15:39:56  shang
# added scan command to format the notenumber into a number
#
# Revision 1.6  2005/03/15 15:34:36  shang
# now the oag technical report homepage is also updated when a revised report is
# submitted; updated the usage message for submitting a new and revised report.
#
# Revision 1.5  2005/02/24 18:18:42  shang
# reformated the category specified report homepage using table
#
# Revision 1.4  2005/01/24 21:14:11  shang
# added checking if the input file is a pdf file and modified the usage message.
#
# Revision 1.3  2005/01/21 22:05:52  shang
# the original oag techincal reports homepage is also updated when a new report
# is submitted.
#
# Revision 1.2  2005/01/21 21:14:22  shang
# comments the part for updating oagTechincalReports.shtml
#
# Revision 1.1  2005/01/21 21:03:49  shang
# first version
#

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSStandardSetup


set CVSRevisionAuthor "\$Revision: 1.43 $ \$Author: soliday $"

proc CreateTableSpecReport {args} {
    set dir /net/helios/Public/operations/ops_www/APSOnly/technicalNotes
    set tmpRoot /tmp/[APSTmpString]
    set files [glob -nocomplain $dir/*Report.sdds]
    if [llength $files] {
        if [catch {eval exec sddscombine $files -pipe=out -merge \
                     | sddssort -pipe -col=Year,decr -unique \
                     | sdds2stream -pipe -col=Year } yearList] {
            return -code error $yearList
        }
    }
    set typeList ""
    foreach file $files {
        set rootname [file tail $file]
        set type [regsub {Report.sdds} $rootname ""]
        if [catch {exec sddsbreak $file \
                     -changeOf=SubCategory $tmpRoot} result] {
            return -code error $result
        }
        if [catch {sdds load $tmpRoot tmpData} result] {
            return -code error $result
        }
        set pages [llength $tmpData(Parameter.Category)]
        set len 1
        for {set page 0} {$page < $pages} {incr page} {
            set subType [lindex [lindex $tmpData(Column.SubCategory) $page] 0]
            set ${type}($subType) [lindex $tmpData(Column.Year) $page]
            lappend ${type}(subType) $subType
        }
        lappend typeList $type
    }
    set typeList [lsort $typeList]
    
    set fd [open "/net/helios/Public/operations/ops_www/APSOnly/oagTechnicalReportsSpec.shtml" "w"]
    puts $fd "<html><head><TITLE>Accelerator Operations and Physics Group Reports</TITLE></head><body bgcolor=white>"
    puts $fd "<P><h1>AOP Technical Reports By Category</h1></P>"
   
    puts $fd "Search Technical Notes<form  ACTION='http://www.aps4.anl.gov/cgi-bin/ops/search-cgi/ksearch3/ksearch.cgi' METHOD='GET' NAME='search' >"
    puts $fd "<input TYPE='text' NAME='terms'><input TYPE='submit' VALUE='Search'>"
    puts $fd "</form>"

    puts $fd "<TABLE BORDER=2 CELLPADDING=3 cellspacing=2>"
    set headerSet "<font face=helvetica size=+1 color=read><b>"
    puts $fd "<TR> <th bgcolor=#FFCC99> $headerSet Category</TH>"
   
    foreach type $typeList {
        switch $type {
            SW {
                set name "Software"
            }
            NM {
                set name "Numerical Methods"
            }
            SR {
                set name "Storage Ring"
            }
            default {
                set name $type
            }
        }
        set len [llength [set ${type}(subType)]]
        puts $fd "<th bgcolor=#FFCC99 COLSPAN=$len>$headerSet $name</TH>"
    }
    puts $fd "</TR>"
    set headerset1 "<font face=helvetica color=blue><b>"
    puts $fd "<TR> <TH bgcolor=#FFCC99> $headerset1 SubCategory</TH>"
    foreach type $typeList {
        foreach subType [set ${type}(subType)] {
            puts $fd "<TH bgcolor=#FFCC99> $headerset1 $subType</TH>"
        }
    }
    puts $fd "</TR>"
    puts $fd "<TR>"
    set headerSet1 "<font face=helvetica size=+1 color=red><b>"
    set dir "http://www.aps4.anl.gov/operations/ops_www/APSOnly"
    foreach year $yearList {
        if {$year<=0} {
            continue
        }
        puts $fd "<TH bgcolor=#FFFFCC> $headerSet1 $year</TH>"
        foreach type $typeList {
            foreach subtype [set ${type}(subType)] {
                set years [set ${type}($subtype)]
                if [lsearch -exact $years $year]>=0 {
                    puts $fd "<td align=center><a href=$dir/technicalNotes/${type}_${subtype}_${year}.html><img src=$dir/blue_ball.gif width=14 height=14></a></td>"
                } else {
                    puts $fd "<TD>&nbsp;</TD>"
                }
            }
        }
        puts $fd "</tr>"
    }
    puts $fd "</TABLE>"
    puts $fd "</body></html>"
    close $fd
}

proc CreateOAGTechReportHomePage {args} {
    set inputDir ""
    set htmlDir ""
    APSParseArguments {htmlDir inputDir}

    set tmpRoot /tmp/[APSTmpString]
    set fileList [lsort [glob -nocomplain $inputDir/technicalNotes/*Report.sdds]]
    if ![llength $fileList] {
        return -code error "CreateOAGTechReportHomePage0: No category files found!"
    }
    set htmlFile $inputDir/oagTechnicalReportsSpec.shtml
    set fd [open $htmlFile "w"]
    puts $fd "<html><head><TITLE>Accelerator Operations and Physics Group Reports</TITLE></head><body bgcolor=white>"
    puts $fd "<P><h1>AOP Technical Reports By Category</h1></P>"
    foreach file $fileList {
        set category [exec sdds2stream -par=Category $file]
        switch $category {
            NM {
                set category "Numerical Methods"
            }
            SR {
                set category "Storage Ring"
            }
            SW {
                set category "Software"
            }
        }
        puts $fd "<p><h2><b>$category</h2>"
        if [catch {exec sddssort $file -col=SubCategory -unique -pipe=out \
                     | sdds2stream -pipe -col=SubCategory } subcategories] {
            return -code error $subcategories
        }
        set len [llength $subcategories]
        puts $fd "<font size=\"+2\"><PRE>" 
        foreach sub $subcategories {
            APSAddToTmpFileList -ID oagSubmitReport -fileList $tmpRoot.$sub
            if [catch {exec sddsprocess $file $tmpRoot.$sub -match=col,SubCategory=$sub } result] {
                return -code error $result
            }
            set yearList [exec sdds2stream $tmpRoot.$sub -col=Year]
            set linkList [exec sdds2stream $tmpRoot.$sub -col=link_name]

            if [string compare $sub "General"]==0 {
                if {$len>1} {
                    puts $fd "<b>$sub<br>" 
                }
            } else {
                puts $fd "<b>$sub<br>" 
            }
            set links ""
            foreach year $yearList link $linkList {
                append links "<a href=\"$htmlDir/technicalNotes/$link\">$year</a>  "
            }
            puts $fd $links
            puts $fd "<br>"
        }
        puts $fd "</PRE></font></p>"
    }
    set date [clock format [clock seconds] -format "%m/%d/%Y"]
    puts $fd "\n\n"
    puts $fd "<A HREF=\"/asd/controls/epics_copyright.html\">Copyright Notice</A>"
    puts $fd "modified $date by <a href=\"mailto:soliday@aps.anl.gov\">shang@aps.anl.gov</a>"
    puts $fd "<!--#exec cmd=\"/Public/Accelerator_Systems_Division/Accelerator_Operations_Physics/cgi-bin/oagLog.cgi 'oagTechnicalReports.html'\"-->"
    puts $fd "</body></html>"
    close $fd 
}

proc CreateReportCategoryFile {args} {
    set category ""
    set subcategory ""
    set year ""
    set inputDir ""
    set htmlDir ""
    APSStrictParseArguments {category subcategory year inputDir htmlDir}
    
    set tmpRoot /tmp/[APSTmpString]
    set report $inputDir/technicalNotes/${category}Report.sdds
    puts $report
    if [string length $subcategory] {
        set sub $subcategory
    } else {
        set sub General
    }
    set changed 0
    if ![file exist $report] {
        if [catch {exec sddsmakedataset $report \
                     -par=Category,type=string -data=$category  \
                     -col=SubCategory,type=string -data=$sub \
                     -column=Year,type=short -data=$year \
                     -col=link_name,type=string -data=${category}_${sub}_$year.html} result] {
            return -code error "CreateReportCategoryFile: $result"
        }
        set changed 1
    } else {
        if [catch {exec sddsprocess $report $tmpRoot.1 \
                     -match=col,SubCategory=$sub -nowarnings } result] {
            return -code error "CreateReportCategoryFile: $result"
        }
        APSAddToTmpFileList -ID oagSubmitReport -fileList $tmpRoot.1
        set yearList [exec sdds2stream $tmpRoot.1 -col=Year]
        if [lsearch $yearList $year]<0 {
            APSAddToTmpFileList -ID oagSubmitReport -fileList $tmpRoot.2
            if [catch {exec sddsmakedataset $tmpRoot.2 \
                         -par=Category,type=string "-data=$category"  \
                         -col=SubCategory,type=string "-data=$sub" \
                         -column=Year,type=short -data=$year \
                         -col=link_name,type=string -data=${category}_${sub}_$year.html} result] {
                return -code error "CreateReportCategoryFile: $result"
            }
            if [catch {exec sddscombine $report $tmpRoot.2 -pipe=out -merge \
                         | sddssort -pipe=in $report -col=SubCategory -col=Year,decreasing } result] {
                return -code error "CreateReportCategoryFile: $result"
            }
            set changed 1
        }
    }  

    return $changed
}


proc CreateReportLogFile {args} {
    set year ""
    set filename ""
    set title ""
    set author ""
    set category ""
    set subcategory ""
    set noteNumber ""
    set revision 0
    set date ""
    set ndate ""
    set inputDir ""
    set htmlDir ""
    APSParseArguments {year filename title author category subcategory noteNumber revision date inputDir htmlDir ndate}
    
    set newReport 0
    set nameList {year filename title author category date}    
    set logFile $inputDir/technicalNotes/${year}.log
    
    if {![string length $revision] || !$revision || ![file exist $logFile]} {
        foreach name $nameList {
            if ![string length [set $name]] {
                return -code error "CreateReportLogFile1: $name is not given!"
            }
        }
    }
    if [string length $subcategory] {
        set sub $subcategory
    } else {
        set sub General
    }
    set changed 0
    set oldDir [pwd]
    #cd $inputDir/technicalNotes
  
    if {![string match "tnote*" $filename]} {
        if ![string length $noteNumber] {
            if ![file exists $logFile] {
                set noteNumber 1
            } else {
                if [catch {exec sddssort $logFile -pipe=out -column=NoteNumber,incr | sddsprocess -pipe -clip=0,1,invert | sdds2stream -pipe -column=NoteNumber} noteNumber] {
                    return -code error "$noteNumber"
                }
                set noteNumber [expr $noteNumber+1]
            }
            set newReport 1
        }
        global tnoteNumber
        set tnoteNumber $noteNumber
        if {$revision>0} {
            set extension [format %03d $noteNumber]R[format %02d $revision].pdf
        } else {
            set extension [format %03d $noteNumber]R00.pdf
        }
        if [file exist $inputDir/technicalNotes/tnote${year}-$extension] {
            return -code error "Error: $inputDir/technicalNotes/tnote${year}-$extension already exists!"
        }
        file copy -force $filename $inputDir/technicalNotes/tnote${year}-$extension
        cd $inputDir/technicalNotes
        set linkfile  tnote${year}-[format %03d $noteNumber].pdf
        set filename tnote${year}-$extension
        if [file exist $linkfile] {
            exec rm $linkfile
        }
     
        exec ln -s $filename $linkfile
        cd $oldDir
        set filename $linkfile
    } else {
        return -code error "Invalid filename provided, should not use tnote* for filename."
    }
    
    set tmpRoot /tmp/[APSTmpString]
    APSAddToTmpFileList -ID oagSubmitReport -fileList "$tmpRoot.1 $tmpRoot.2 $tmpRoot.3 $tmpRoot.4"
    if [file exist $logFile] {
        if $newReport {
            set rows 0
            exec cp $logFile $tmpRoot.2
        } else {
            if [catch {exec sddsprocess $logFile -nowarnings\
                         -filter=col,NoteNumber,$noteNumber,$noteNumber $tmpRoot.1 } result] {
                return -code error "CreateReportLogFile2: $result"
            }
            set rows [exec sdds2stream $tmpRoot.1 -rows=bare]
            if [catch {exec sddsprocess $logFile $tmpRoot.2 -nowarnings \
                         -filter=col,NoteNumber,$noteNumber,$noteNumber,! } result] {
                return -code error  "CreateReportLogFile3: $result"
            }
        }
        if !$rows {
            set newReport 1
            if [catch {exec sddsmakedataset $tmpRoot.3 -col=Filename,type=string -data=$filename \
                         -col=Year,type=short -data=$year\
                         -col=NoteNumber,type=long -data=$noteNumber \
                         -col=Revision,type=short -data=$revision \
                         -col=Author,type=string "-data=[APSMakeSafeQualifierString $author]" \
                         -col=Date,type=string "-data=[APSMakeSafeQualifierString $date]" \
                         -col=NDate,type=string -data=$ndate \
                         -col=OldDesignation,type=string -data= \
                         -col=Category,type=string "-data=[APSMakeSafeQualifierString $category]" \
                         -col=SubCategory,type=string "-data=[APSMakeSafeQualifierString $sub]" \
                         -col=Title,type=string "-data=[APSMakeSafeQualifierString $title]" } result] {
                return -code error  "CreateReportLogFile4: $result"
            }
            set changed 1
        } else {
            set rev [exec sdds2stream $tmpRoot.1 -col=Revision]
            if {$rev!=$revision} {
                if [catch {exec sddsprocess $tmpRoot.1 $tmpRoot.3 -reprint=col,Filename,$filename \
                             "-reprint=col,Title,[APSMakeSafeQualifierString $title]" \
                             -redefine=col,Revision,$revision,type=short \
                             "-reprint=col,Date,[APSMakeSafeQualifierString $date]" } result] {
                    return -code error  "CreateReportLogFile5: $result"
                }
                set changed 1
            }
        }
        if {$changed} {
            if [catch {exec sddscombine $tmpRoot.2 $tmpRoot.3 -pipe=out -merge \
                         | sddssort -pipe=in $logFile -col=NoteNumber,decreasing } result] {
                return -code error  "CreateReportLogFile6: $result"
            }
        }
    } else {
        set changed 1
        set newReport 1
        if [catch {exec sddsmakedataset $logFile -col=Filename,type=string -data=$filename \
                     -col=Year,type=short -data=$year\
                     -col=NoteNumber,type=long -data=$noteNumber \
                     -col=Revision,type=short -data=$revision \
                     -col=Author,type=string "-data=[APSMakeSafeQualifierString $author]" \
                     -col=Date,type=string "-data=[APSMakeSafeQualifierString $date]" \
                     -col=NDate,type=string -data=$ndate \
                     -col=OldDesignation,type=string -data= \
                     -col=Category,type=string "-data=[APSMakeSafeQualifierString $category]" \
                     -col=SubCategory,type=string "-data=[APSMakeSafeQualifierString $sub]" \
                     -col=Title,type=string "-data=[APSMakeSafeQualifierString $title]" } result] {
            return -code error  "CreateReportLogFile7: $result"
        }
    }
    APSDeleteTmpFileList -ID sumbitReport
  #  cd $oldDir
    return $changed
}

proc CreateLinkedHtml {args} {
    set htmlDir ""
    set category ""
    set subcategory ""
    set year ""
    set inputDir ""
    APSParseArguments {category subcategory htmlDir year inputDir}
    
    if ![string length $subcategory] {
        set subcategory General
    }
    set htmlFile $inputDir/technicalNotes/${category}_${subcategory}_${year}.html
    set file $inputDir/technicalNotes/${year}.log
    set tmpRoot /tmp/[APSTmpString]
    APSAddToTmpFileList -ID oagSubmitReport -fileList "$tmpRoot.1"
    
    if [catch {exec sddsprocess $file \
                 "-match=col,Category=$category,SubCategory=$subcategory,&" $tmpRoot.1 } result] {
        return -code error "CreateLinkedHtml0: $result"
    }
    if [catch {sdds load $tmpRoot.1 data} result] {
        return -code error "CreateLinkedHtml1: $result"
    }
    set noteList [lindex $data(Column.NoteNumber) 0]
    set titleList [lindex $data(Column.Title) 0]
    set authorList [lindex $data(Column.Author) 0]
    set revisionList [lindex $data(Column.Revision) 0]
    set dateList [lindex $data(Column.Date) 0]
    set fileList [lindex $data(Column.Filename) 0]
    set oldDesignationList [lindex $data(Column.OldDesignation) 0]
    set fd [open $htmlFile "w"]
    puts $fd "<html><head><TITLE>Accelerator Operations and Physics Group Reports</TITLE></head><body bgcolor=white>"
    puts $fd "<P><h1>AOP Technical Reports ($category, $year)</h1></P>"
    foreach file $fileList num $noteList date $dateList author $authorList rev $revisionList title $titleList oldDesignation $oldDesignationList {
        if {$rev>0} {
            set note "AOP-TN-$year-[format %03d $num] Rev.$rev"
        } else {
            set note "AOP-TN-$year-[format %03d $num]"
        }
        if [string length $oldDesignation] {
            set note "$oldDesignation ($note)"
        }
        puts $fd "<p><li><b>$title</b>, $note<br>$author ($date) - <a href=\"$htmlDir/technicalNotes/$file\">PDF</a></p>"
        puts $fd ""
    }
    puts $fd ""
    set date [clock format [clock seconds] -format "%m/%d/%Y"]
    puts $fd "<A HREF=\"/asd/controls/epics_copyright.html\">Copyright Notice</A>"
    puts $fd "modified $date by <a href=\"mailto:shang@aps.anl.gov\">shang@aps.anl.gov</a>"
    puts $fd "<!--#exec cmd=\"/Public/Accelerator_Systems_Division/Accelerator_Operations_Physics/cgi-bin/oagLog.cgi 'oagTechnicalReports.html'\"-->"
    puts $fd "</body></html>"
    close $fd
}

proc UpdateOAGTechReportPage {args} {
    set htmlDir  http://www.aps4.anl.gov/operations/ops_www/APSOnly
    set inputDir /net/helios/Public/operations/ops_www/APSOnly
    APSParseArguments {htmlDir inputDir}
    set dir $inputDir/technicalNotes
    set tmpRoot /tmp/[APSTmpString]
    set files [lsort -decreasing [glob -nocomplain $dir/????.log]]
    set htmlFile $inputDir/oagTechnicalReports.html
    if [llength $files] {
        if [catch {eval exec sddscombine $files  -pipe=out -merge \
                     | tee $tmpRoot.1 \
                     | sddsprocess -pipe -filter=col,Revision,0,0,! \
                     | sddsprocess -pipe=in $tmpRoot.1a \
                     \"-reprint=col,NoteText,AOP-TN-%d-%03dRev.%d,Year,NoteNumber,Revision\" } result] {
            return -code error $result
        }
        if [catch {exec sddsprocess $tmpRoot.1 $tmpRoot.1b -filter=col,Revision,0,0 \
                     -reprint=col,NoteText,AOP-TN-%d-%03d,Year,NoteNumber } result] {
            return -code error $result
        }
        if [catch {exec sddscombine $tmpRoot.1a $tmpRoot.1b -pipe=out -merge \
                     | sddssort -col=NDate,decreasing -col=NoteNumber,decreasing -pipe=in $tmpRoot.1} result] {
            return -code error $result
        }
    }
    APSAddToTmpFileList -ID 1 -fileList $tmpRoot.1
    set filenameList [exec sdds2stream -col=Filename $tmpRoot.1]
    set noteList [exec sdds2stream -col=NoteText $tmpRoot.1]
    set dateList [exec sdds2stream -col=Date $tmpRoot.1]
    set titleList [exec sdds2stream -col=Title $tmpRoot.1]
    set authorList [exec sdds2stream -col=Author $tmpRoot.1]    
    set oldDesignationList [exec sdds2stream -col=OldDesignation $tmpRoot.1]    
    set fd [open $htmlFile w]
    puts $fd "<html><head><title>Accelerator Operations and Physics Group Reports</title></head><body bgcolor=white>"
    puts $fd ""
    puts $fd "<p><h1>AOP Technical Reports</h1></p>"
    puts $fd "Search Technical Notes<form  ACTION='http://www.aps4.anl.gov/cgi-bin/ops/search-cgi/ksearch3/ksearch.cgi' METHOD='GET' NAME='search' >
<input TYPE='text' NAME='terms'><input TYPE='submit' VALUE='Search'>
</form><p>"

    foreach title $titleList author $authorList note $noteList date $dateList file $filenameList oldDesignation $oldDesignationList {
        puts -nonewline $fd "<p><li><b>${title},</b> "
        if [string length $oldDesignation] {
            puts -nonewline $fd "$oldDesignation"
        } else {
            puts -nonewline $fd "$note"
        }
        puts  $fd "<br>$author ($date)- <a href=\"$htmlDir/technicalNotes/${file}\">PDF</a></p>"
        puts $fd ""
    }
    puts $fd ""
    set date [clock format [clock seconds] -format "%m/%d/%Y"]
    puts $fd "<a href=\"/asd/controls/epics_copyright.html\">Copyright Notice</a>"
    puts $fd "modified $date by <a href=\"mailto:shang@aps.anl.gov\">shang@aps.anl.gov</a>"
    puts $fd "<!--#exec cmd=\"/Public/Accelerator_Systems_Division/Accelerator_Operations_Physics/cgi-bin/oagLog.cgi 'oagTechnicalReports.html'\"-->"
    puts $fd "</body></html>"
    close $fd
}


proc SendEmailAnnouncement {args} {
    set category None
    set author None
    set title None
    set revision 0
    APSParseArguments {category author title revision}

    if ![file exists /net/helios/Public/operations/ops_www/APSOnly/technicalNotes/mailingList.sdds] {
        return -code error "No mailing list file!"
    }
    set mailingList [join [exec sdds2stream -column=Address /net/helios/Public/operations/ops_www/APSOnly/technicalNotes/mailingList.sdds] ","]
    if $revision==0 {
        set text "A new technical note is available by $author on \"$title\".  Please see http://www.aps4.anl.gov/operations/ops_www/APSOnly/oagTechnicalReports.html"
        catch {exec echo "$text" | mailx -s "New AOP technical note" $mailingList} result
    }
}

proc PromptForCategories {args} {
    #Categories
    set categories [APSGetValidICMSTechReportCategories]
    set selection ""
    while {![string is integer $selection] || \
             ([llength [string trim $selection]] != 1) || \
             ($selection < 0) || \
             ($selection >= [llength $categories])} {
        puts "\nAvailable ICMS \"Categories\":"
        set i 0
        foreach category $categories {
            puts "($i) $category"
            incr i
        }
        puts -nonewline "Select a \"Category\": "
        flush stdout
        gets stdin selection
        set selection [string trim $selection]
    }
    set xTopicLevel3 [lindex $categories $selection]

    #Sub-Categories
    set subcategories [APSGetValidICMSTechReportSubCategories -category $xTopicLevel3]
    set selection ""
    while {![string is integer $selection] || \
             ([llength [string trim $selection]] != 1) || \
             ($selection < 0) || \
             ($selection >= [llength $subcategories])} {
        puts "\nAvailable ICMS \"Sub-Categories\":"
        set i 0
        foreach subcategory $subcategories {
            puts "($i) $subcategory"
            incr i
        }
        puts -nonewline "Select a \"Sub-Category\": "
        flush stdout
        gets stdin selection
        set selection [string trim $selection]
    }
    set xTopicLevel4 [lindex $subcategories $selection]

    return "-xTopicLevel3 \"$xTopicLevel3\" -xTopicLevel4 \"$xTopicLevel4\""
}

puts "this application is obsolete, please use following webpage to submit the tech note\nhttp://www.aps4.anl.gov/asd/oag/cgi-bin/submitICMS.cgi\n"
exit 0
set inputDir /net/helios/Public/operations/ops_www/APSOnly
set htmlDir http://www.aps4.anl.gov/operations/ops_www/APSOnly

set args $argv
set filename ""
set category ""
set subcategory General
set title ""
set help 0
set revision 0
set noteNumber ""
set author ""
set date ""
set year ""
set noteYear ""
set update 0
set usage "usage: OAGSubmitTechReport -filename <filename of report> -title <title of report>\n   -category <type of report> -author <names> \[-subcategory <string>\] \[-help <1>\]\n   \[-date <month/day/year>\] \[-noteNumber <year-number>\] \[-revision <number>\]\n\n<filename> should be pdf format and with .pdf extension.\n<category> may be: Linac, Booster, PAR, SR, NM, General or Software, while\n       SR represents \"Storage Ring\"\n       NM represents \"Numerical & Simulation Methods\"\n<subcategory> is optional.\n<date> is the date when report was created.\n       It is required if submit a not-today's report.\n<noteNumber> and <revision> are optional.\n     They are required for submitting a revised version to replace an existing report.\n\nEg. to submit a new report, use following command:\nOGSumbitTechReport -filename <filename> -title <title> -author <list of authors>\n\nTo submit a revised report, use following command (an example):\nOAGSubmitTechReport -filename <filename> -title <title> -author <author> \n                    -noteNumber 2006-007 -revision 1\n"
APSParseArguments {filename category help title revision noteNumber author date subcategory update}

if {[string compare $env(USER) "oag"]!=0 } {
    puts stderr "Only oag (user) can submit technical report!"
    exit 1
}
if {[string compare $env(HOST) "challenger"]!=0} {
    puts stderr "Please log into challenger as oag to submit technical support!"
    exit 1
}

if {![llength $argv] || $help} {
    puts stderr "$usage"
    exit
}

if ![file exist $filename] {
    puts stderr "$filename does not exist! You need provide the file path if it is not in current directory."
    exit
}

if !$update {
    if ![string length $filename] {
        puts stderr "filename is not given!\n$argv"
        exit
    }
    
    set ext [string tolower [file extension $filename]]
    if [string compare $ext ".pdf"]!=0 {
        puts stderr "filename is not a pdf file!"
        exit
    }
    if ![string length $category] {
        puts stderr "category is not provided!\n$argv"
        exit
    }
    if ![string length $title] {
        puts stderr "report title is not given!\n$argv"
        exit
    }
    
    if ![string length $author] {
        puts stderr "author is not given!\n$argv"
    }
    if ![string match "tnote*" $filename] {
        if ![file exist $filename] {
            puts stderr "$filename does not exist!"
            exit
        }
    }
    set noteNumber [regsub {AOP-TN-} $noteNumber ""]
    set noteNumber [regsub {OAG-TN-} $noteNumber ""]
    #do not allow installing a note with a revision number if the technote number isn't also given.
    if {$revision && ![string length $noteNumber]} {
        puts stderr "Error: the noteNumber has to provided if the revision number is provided."
        exit   
    } 
    
    if !$revision {
        #check if the title exists in previous notes.
        set tmpFile /tmp/[APSTmpString]
        APSAddToTmpFileList -ID oagreport -fileList $tmpFile
        set files [glob -nocomplain  /net/helios/Public/operations/ops_www/APSOnly/technicalNotes/????.log]
        if [catch {eval exec sddscombine $files -merge -pipe=out \
                     | sddsprocess -pipe=in $tmpFile -nowarnings \
                     \"-match=col,Title=[APSMakeSafeQualifierString [APSMakeSafeQualifierString $title]]\" } result] {
            puts stderr "Error1: Checking existing titles: $result"
            exit
        }
        
        set rows [exec sdds2stream -rows=bar $tmpFile]
        if $rows {
            puts stderr "Error: title - \"$title\" already exists in previous note."
            exit
        }
    }
    
    if ![string length $date] {
        set time [clock seconds]
        set year [clock format $time -format "%Y"]
        set date [clock format $time -format "%B %d, %Y"]
    } else {
        set time [clock scan $date]
        set year [clock format $time -format "%Y"]
        set date [clock format $time -format "%B %d, %Y"]
    }
    set ndate [clock format $time -format "%Y/%m/%d"]
    if [regexp {\-} $noteNumber] {
        set strList [split $noteNumber -]
        set noteYear [lindex $strList 0]
        set noteNumber [scan [lindex $strList 1] %ld]
    }
    if {[string length $revision] && $revision>0} {
        if ![string length $noteYear] {
            set noteYear [clock format [clock seconds] -format "%Y"]
        }         
    } else {
        set noteYear $year
    }
    set type1 [string tolower $category]
    if [string match "numerical method*" $type1] {
        set category NM
    } elseif [string match "software" $type1] {
        set category SW
    } elseif [string match "storage ring" $type1] {
        set category SR
    } elseif [string match "par" $type1] {
        set category PAR
    } elseif [string match "booster" $type1] {
        set category Booster
    } elseif [string match "linac" $type1] {
        set category Linac
    } elseif [string match "general" $type1] {
        set category General
    }

    set categoryList {NM SW SR PAR Booster Linac General}
    if [lsearch $categoryList $category]<0 {
        puts stderr "Unknown category -- $category\nThe category may be\nBooster, General, Linac, \"Numerical Method\"(or NM), PAR, \"Storage Ring\"(or SR), or Software(or SW)!"
        exit
    }
    if ![string length $subcategory] {
        set subcategory General
    }
    puts $title

    #PREPARE TO SUBMIT FILE TO ICMS
    if {$revision} {
        set submitICMSRevision 0
        if {[catch {APSICMSQueryDocNameAndRevision \
                      -dDocTitle [APSMakeSafeQualifierString [APSMakeSafeQualifierString $title]] \
                      -dDocType "Report" \
                      -xComments "TechReport" \
                      -xDivision ASD \
                      -xGroup AOP \
                      -icmsPassword \$And56reW \
                      -icmsUsername aopsoap} results]} {
            catch {exec echo "$results : [APSMakeSafeQualifierString [APSMakeSafeQualifierString $title]] " | mailx -s "technical note to ICMS failure1" soliday@aps.anl.gov} result
        } else {
            set dDocName [lindex $results 0]
            set dRevLabel [lindex $results 1]
            
            if {[catch {APSICMSQueryTopicLevels \
                          -dDocName $dDocName \
                          -dRevLabel $dRevLabel \
                          -icmsPassword \$And56reW \
                          -icmsUsername aopsoap} results]} {
                catch {exec echo "$results : $dDocName : $dRevLabel " | mailx -s "technical note to ICMS failure2" soliday@aps.anl.gov} result
            } else {
                set xTopicLevel1 [lindex $results 0]
                set xTopicLevel2 [lindex $results 1]
                set xTopicLevel3 [lindex $results 2]
                set xTopicLevel4 [lindex $results 3]
                incr dRevLabel
                set submitICMSRevision 1
            }
        }
    } else {
        set args [PromptForCategories]
        APSStrictParseArguments {xTopicLevel3 xTopicLevel4}

    }

    if [catch {CreateReportCategoryFile -category $category -inputDir $inputDir \
                 -subcategory $subcategory -year $noteYear} result] {
        puts stderr $result
        exit
    }
    if {$result} {
        if [catch {CreateTableSpecReport} result] {
            puts stderr $result
            exit
        }
    }
    set tnoteNumber $noteNumber
    if [catch {CreateReportLogFile -year $noteYear -filename $filename \
                 -title $title -author $author -category $category \
                 -subcategory $subcategory -noteNumber $noteNumber \
                 -revision $revision -date $date -ndate $ndate -inputDir $inputDir -htmlDir $htmlDir } result] {
        puts stderr $result
        exit
    }
    if {$result} {
        if [catch {CreateLinkedHtml -htmlDir $htmlDir -inputDir $inputDir \
                     -category $category -subcategory $subcategory -year $noteYear} result] {
            puts stderr $result
            exit
        }
        if [catch {UpdateOAGTechReportPage -htmlDir $htmlDir -inputDir $inputDir} result] {
            puts stderr $result
            exit
        }
        catch {exec echo "OAGSubmitTechReport DEBUG1 " | mailx -s "OAGSubmitTechReport DEBUG1" soliday@aps.anl.gov} result

        if [catch {SendEmailAnnouncement -category $category -author $author -title $title -revision $revision} result] {
            puts stderr "$result"
            exit
        }
        if {$revision} {
            catch {exec echo "OAGSubmitTechReport DEBUG2 " | mailx -s "OAGSubmitTechReport DEBUG2" soliday@aps.anl.gov} result
            if {$submitICMSRevision} {
                if {[catch {APSSubmitFileToICMS \
                              -primaryFile $filename \
                              -dDocName $dDocName \
                              -dDocTitle [APSMakeSafeQualifierString [APSMakeSafeQualifierString $title]] \
                              -xDocAuthor $author \
                              -dDocAuthor aopsoap \
                              -xComments "TechReport:AOP-TN-$noteYear-[format %03d $tnoteNumber]Rev.$revision " \
                              -dRevLabel $dRevLabel \
                              -xDocDate $date \
                              -dSecurityGroup APS \
                              -dDocAccount APSShare/AcceleratorOperationsPhysics \
                              -icmsUsername aopsoap \
                              -icmsPassword \$And56reW \
                              -xDivision ASD \
                              -xGroup AOP \
                              -xTopicLevel1 "Technical Documentation" \
                              -xTopicLevel2 "Technical Notes" \
                              -xTopicLevel3 $xTopicLevel3 \
                              -xTopicLevel4 $xTopicLevel4} results]} {
                    catch {exec echo "$results : AOP-TN-$year-[format %03d $tnoteNumber] $xTopicLevel3 $xTopicLevel4 " | mailx -s "technical note to ICMS failure3" soliday@aps.anl.gov} result
                }
            }
        } else {
            catch {exec echo "OAGSubmitTechReport DEBUG3 " | mailx -s "OAGSubmitTechReport DEBUG3" soliday@aps.anl.gov} result
            if {[catch {APSSubmitFileToICMS \
                          -primaryFile $filename \
                          -dDocTitle [APSMakeSafeQualifierString [APSMakeSafeQualifierString $title]] \
                          -xDocAuthor $author \
                          -dDocAuthor aopsoap \
                          -xComments "TechReport:AOP-TN-$noteYear-[format %03d $tnoteNumber] " \
                          -dRevLabel 0 \
                          -xDocDate $date \
                          -dSecurityGroup APS \
                          -dDocAccount APSShare/AcceleratorOperationsPhysics \
                          -icmsUsername aopsoap \
                          -icmsPassword \$And56reW \
                          -xDivision ASD \
                          -xGroup AOP \
                          -xTopicLevel1 "Technical Documentation" \
                          -xTopicLevel2 "Technical Notes" \
                          -xTopicLevel3 $xTopicLevel3 \
                          -xTopicLevel4 $xTopicLevel4} results]} {
                catch {exec echo "$results : AOP-TN-$year-[format %03d $tnoteNumber] $xTopicLevel3 $xTopicLevel4 " | mailx -s "technical note to ICMS failure4" soliday@aps.anl.gov} result
            }
        }
        catch {exec echo "OAGSubmitTechReport DEBUG4 " | mailx -s "OAGSubmitTechReport DEBUG4" soliday@aps.anl.gov} result
        catch {exec echo "OAGSubmitTechReport DEBUG5 $results " | mailx -s "OAGSubmitTechReport DEBUG5" soliday@aps.anl.gov} result

    }
} else {
    if [catch {UpdateOAGTechReportPage -htmlDir $htmlDir -inputDir $inputDir} result] {
        puts stderr $result
        exit
    }
}


APSDeleteTmpFileList -ID oagSubmitReport

exit
