# Copyright (c) 1993 by Sanjay Ghemawat
#
# Startup script for X-based ical

############################################################################
# Initialize search paths

if [catch {set libdir $env(ICAL_LIBRARY)}] {
    puts stderr "ical: could not find support library"
    exit 1
}

if [catch {set auto_path}] {
    set auto_path ""
}
set auto_path [concat $libdir $libdir/tcllib $auto_path]
set icon_path [concat $libdir $libdir/tcllib]

support_init

############################################################################
# Parse arguments

set iconic 0
set mono 0
set popup 0
set cmdopts {}

# Tk initialization already parsed -geometry for us
if [catch {set geometry}] {
    set geometry ""
}

while {[llength $argv] != 0} {
    set arg [lindex $argv 0]
    set argv [lrange $argv 1 end]

    case $arg in {
        "-iconic" {
	    set iconic 1
        }

	"-calendar" {
	    if {[llength $argv] < 1} usage
	    set calfile [lindex $argv 0]
	    set argv [lrange $argv 1 end]
	}

	"-mono" {
	    set mono 1
	}

	"-popup" {
	    set popup 1
	}

	"-bg" {
	    if {[llength $argv] < 1} usage
	    set bg [lindex $argv 0]
	    set argv [lrange $argv 1 end]

	    lappend cmdopts "option add *Background $bg"
	}

	"-fg" {
	    if {[llength $argv] < 1} usage
	    set fg [lindex $argv 0]
	    set argv [lrange $argv 1 end]

	    lappend cmdopts "option add *Foreground $fg"
	}

	default {
	    usage
	}
    }
}

############################################################################
# Get calendar

calendar cal $calfile

############################################################################
# Window interaction

# Handle background errors
proc tkerror {message} {
    global mailer author_mail errorInfo ical_version

    set message "Ical Version $ical_version\n\n$message\n\nTrace:\n$errorInfo"
    bug_notify $mailer $author_mail $message
}

# Remove default window
wm withdraw .

# Monochrome?
if {$mono} {
    tk colormodel . monochrome
}

# Initialize user preferences
pref init
foreach opt $cmdopts {
    eval $opt
}

# Fix bindings to more reasonable values
fix_bindings

if {$popup} {
    # Create item listing
    set l [ItemListing]
    $l mainwindow
    $l dayrange [date today] [date today]
    if {$geometry != ""} {
	wm geometry [$l window] $geometry
    }
} else {
    # Periodically save/reread
    io_thread

    # Show alarms
    start_alarmer

    # Create initial view
    set dv [DayView]
    if {$iconic} {
	wm iconify [$dv window]
    }
    if {$geometry != ""} {
	wm geometry [$dv window] $geometry
    }
}
