#!/usr/bin/wish

#tk_setPalette #4499ff

set basedir [file dirname $argv0]

regsub {/bin$} $basedir {} basedir

if { $basedir == "" } {
	set basedir [exec which $argv0]
}

if { $basedir == "" } {
	set basedir "/cv/"
}

set tkimages "$basedir/tkimages"
set libdir "$basedir"
set tkpatients "/ct"

if { [array names env ECCET_PATIENTBASE] != "" } {
	set tkpatients $env(ECCET_PATIENTBASE)
}

if { ! [file isdirectory $tkimages] } {
	set tkimages "$basedir/lib/eccet/tkimages"
	set libdir "$basedir/lib/eccet"
}

if { ! [file isdirectory $tkimages] } {
	puts stderr "Cannot find button images. Please give basedir."
	exit
}

set tkscripts "$basedir/batches"

if { ! [file isdirectory $tkscripts] } {
	set tkscripts "$basedir/lib/eccet/batches"
}

if { ! [file isdirectory $tkscripts] } {
	puts stderr "Cannot find script directory. Please give basedir."
	exit
}

#
# Hide Main window while building it.
#
wm withdraw .

frame .patients -borderwidth 1 -relief sunken

set patientdir $tkpatients

set selpatient ""

proc rescan_patdir {} {
	global patientdir
	global patientfiles
	regsub -all { [^ ]*/} "[lsort [glob -nocomplain $patientdir/* $patientdir/.* ]]" " " patientfiles
}

proc exec_patient {} {
	global patientdir
	global patientfiles
	global tkpatients
	global selpatient
	set indx [.patients.file curselection]
	if { $indx != "" } {
		set item [.patients.file get $indx]
		if { "$item" == ".." } {
			regsub {/[^/]*$} $patientdir {} patientdir
			if { [ string length $patientdir] < [ string length $tkpatients] } {
				set patientdir $tkpatients
			}
			rescan_patdir
			.patients.sel configure -text "$patientdir"
			.patients.sel configure -foreground "red"
			return
		}
		if { [file isdirectory $patientdir/$item] } {
			set patientdir $patientdir/$item
			rescan_patdir
			.patients.file see 0
			.patients.sel configure -text "$patientdir"
			.patients.sel configure -foreground "red"
			return
		}
		if { [file readable $patientdir/$item] } {
			set selpatient "$patientdir/$item"
			.patients.sel configure -text "$selpatient"
			.patients.sel configure -foreground "darkgreen"
			if { [regexp {^\.CT\.\.[0-9]*\.[0-9.]*.IMA} "$item"] } {
				set result [ tk_messageBox -icon question \
					-message "IMA Stack detected - convert filenames ?" \
	                        	-parent . -type yesno ]
				if { "$result" == "yes" } {
					set dummy [exec convert_ima $patientdir]
					rescan_patdir
					.patients.file see 0
					.patients.sel configure -text "$patientdir"
					.patients.sel configure -foreground "red"
					return
				}
			}
			return
		}
	}
}

proc do_exec {cmdname args} {
	if { ! [file readable $args] } {
		tk_messageBox -icon info -message "No valid file selected." \
                        -parent . -type ok
		return
	}
	set dir [file dirname $args]
	set dir [file dirname $dir]
	cd $dir
#	set dummy [exec xterm -e $cmdname $args &]
	set dummy [exec $cmdname $args &]
}

proc do_convert_braindamage {directory} {

	global patientdir

	if { ! [file readable $directory] } {

		tk_messageBox -icon error -message "Must select a file in the directory you want to convert." \
			-parent . -type ok
		return
	}

	set dir [file dirname $directory]

	set result [ tk_messageBox -icon question \
			-message "Convert all filenames in Directory $dir to value of DICOM-z-Position-Tag ?" \
			-parent . -type yesno ]

	if { "$result" == "yes" } {
		cd $dir
		set dummy [exec convert_braindamage $dir]
		rescan_patdir
		.patients.file see 0
		.patients.sel configure -text "$patientdir"
		.patients.sel configure -foreground "red"
		return
	}
}

label .patients.lab -text "Select patient/dataset:"
label .patients.sel -text "$selpatient"
button .patients.voxren -text "Voxren" -command { do_exec "voxren" "$selpatient" }
button .patients.planeview -text "Planeview" -command { do_exec "planeview" "$selpatient" }
button .patients.convert -text "Conv" -command { do_convert_braindamage "$selpatient" }
listbox .patients.file -listvar patientfiles -height 4 -yscrollcommand ".patients.fscroll set"
scrollbar .patients.fscroll -command ".patients.file yview"
rescan_patdir
bind .patients.file <Double-Button-1> { exec_patient }

proc make_patient {} {

	global patientdir
	global patientfiles
	global tkpatients

	set patientdirtmp [.patients.name get]
	regsub -all {[^a-zA-Z0-9_]} $patientdirtmp {_} patientdirtmp
	.patients.name delete 0 end
	.patients.name insert 0 $patientdirtmp

	set patientdirtmp "$tkpatients/$patientdirtmp"
	if { [file exists $patientdirtmp] } {
		set result [ tk_messageBox -icon info -message "File exists." \
			-parent . -type ok ]
		return
	}
	set result [ tk_messageBox -default "no" -icon question \
		-message "Create new patient directory $patientdirtmp ?" -parent . -title "Quit" \
		-type yesno  ]
	if { "$result" != "yes" } {
		return
	}
	
	file mkdir $patientdirtmp
	file mkdir $patientdirtmp/dicom
	file mkdir $patientdirtmp/3d32
	file mkdir $patientdirtmp/pictures
	set patientdir $patientdirtmp
	rescan_patdir
	.patients.sel configure -text "$patientdir"
	.patients.sel configure -foreground "red"
}

button .patients.new -text "New patient" -command make_patient
entry  .patients.name 
.patients.name insert 0 "New_[clock format [clock seconds] -format "%Y_%d_%m_%H_%M"]"

grid config .patients.lab       -row 0 -column 0 -columnspan 3 -sticky nesw -padx 3 -pady 3
grid config .patients.file      -row 1 -column 0 -columnspan 2 -sticky nesw -padx 3 -pady 3
grid config .patients.fscroll   -row 1 -column 2 -sticky nsw -padx 3 -pady 3
grid config .patients.sel       -row 2 -column 0 -columnspan 3 -sticky nesw -padx 3 -pady 3
grid config .patients.voxren    -row 3 -column 0 -sticky nesw -padx 3 -pady 3
grid config .patients.planeview -row 3 -column 1 -sticky nesw -padx 3 -pady 3
grid config .patients.convert   -row 3 -column 2 -sticky nesw -padx 3 -pady 3
grid config .patients.new       -row 4 -column 0 -sticky nesw -padx 3 -pady 3
grid config .patients.name      -row 4 -column 1 -sticky nesw -padx 3 -pady 3

frame .scripts -borderwidth 1 -relief sunken

set scriptdir $tkscripts
set selscript ""

proc exec_script {} {
	global scriptdir
	global scriptfiles
	global tkscripts
	global selscript
	set indx [.scripts.file curselection]
	if { $indx != "" } {
		set item [.scripts.file get $indx]
		if { "$item" == ".." } {
			regsub {/[^/]*$} $scriptdir {} scriptdir
			if { [ string length $scriptdir] < [ string length $tkscripts] } {
				set scriptdir $tkscripts
			}
			regsub -all { [^ ]*/} ".. [lsort [glob -nocomplain $scriptdir/*]]" " " scriptfiles
			.scripts.sel configure -text "$scriptdir"
			.scripts.sel configure -foreground "red"
			return
		}
		if { [file isdirectory $scriptdir/$item] } {
			set scriptdir $scriptdir/$item
			regsub -all { [^ ]*/} ".. [lsort [glob -nocomplain $scriptdir/*]]" " " scriptfiles
			.scripts.file see 0
			.scripts.sel configure -text "$scriptdir"
			.scripts.sel configure -foreground "red"
			return
		}
		if { [file readable $scriptdir/$item] } {
			set selscript "$scriptdir/$item"
			.scripts.sel configure -text "$selscript"
			.scripts.sel configure -foreground "darkgreen"
			return
		}
	}
}

proc do_exec_stdin {cmdname input args} {
	if { ! [file readable $args] } {
		tk_messageBox -icon info -message "Kein gltiger Datensatz angewhlt." \
                        -parent . -type ok
		return
	}
	if { ! [file readable $input] } {
		tk_messageBox -icon info -message "Kein gltiges Script angewhlt." \
                        -parent . -type ok
		return
	}
	set dir [file dirname $args]
	set dir [file dirname $dir]
	cd $dir
	set dummy [exec xterm -e $cmdname $input $args &]
#	set dummy [exec $cmdname $input $args &]
}

proc showhelp {selscript} {
	if { ! [file readable $selscript] } {
		tk_messageBox -icon info -message "Kein gltiges Script angewhlt." \
                        -parent . -type ok
		return
	}
	set result [exec {sed} {-ne/#HELP /p} "$selscript" | sed {-es/#HELP //} ]
	set result [tk_messageBox -icon info -message "$result" \
			-parent . -type ok ]
}

label .scripts.lab -text "Batchvox scripts:"
label .scripts.sel -text ""
button .scripts.batchvox -text "Batchvox" -command { do_exec_stdin "batchvox" "$selscript" "$selpatient" }
button .scripts.help -text "Help for Script" -command { showhelp "$selscript" }
listbox .scripts.file -listvar scriptfiles -height 4 -yscrollcommand ".scripts.fscroll set"
scrollbar .scripts.fscroll -command ".scripts.file yview"
regsub -all { [^ ]*/} ".. [lsort [glob -nocomplain $scriptdir/*]]" " " scriptfiles
bind .scripts.file <Double-Button-1> { exec_script }

grid config .scripts.lab      -row 0 -column 0 -columnspan 3 -sticky nesw -padx 3 -pady 3
grid config .scripts.file     -row 1 -column 0 -columnspan 2 -sticky nesw -padx 3 -pady 3
grid config .scripts.fscroll  -row 1 -column 2 -sticky nsw -padx 3 -pady 3
grid config .scripts.sel      -row 2 -column 0 -columnspan 3 -sticky nesw -padx 3 -pady 3
grid config .scripts.batchvox -row 3 -column 0 -sticky nesw -padx 3 -pady 3
grid config .scripts.help     -row 3 -column 1 -sticky nesw -padx 3 -pady 3

frame .status -borderwidth 1 -relief sunken

proc do_quit {} {
	set result [ tk_messageBox -default "no" -icon question \
		-message "Quit program ?" -parent . -title "Quit" \
		-type yesno  ]
	if { "$result" == "yes" } {
		exit
	}
}

button .status.quit -text "Quit" -command "do_quit"
button .status.help -text "Help" -command "exec eccet_help &"

grid config .status.help -row 0 -column 0 -sticky ew -padx 3 -pady 3
grid config .status.quit -row 0 -column 2 -sticky ew -padx 3 -pady 3

pack .patients .scripts .status -side top -fill x -padx 1 -pady 1

wm deiconify .

