set scriptDir [file normalize [file join [file dirname [info script]]]]
set auto_path [linsert $auto_path 0 $scriptDir]

package require Tk

package require autoscroll
package require PuppyIcons
package require tooltip
package require inifile

package require jigsaw

proc PrintUsage { progName } {
    puts "Usage: $progName \[Options\] \[puzzleFile\]"
    puts "Start the Jigsaw Puzzler"
    puts ""
    puts "Options:"
    puts "--play      : Start in play-only mode."
    puts "--fullscreen: Start in full-screen mode."
}

###################################################
# Main 
###################################################

jigsaw-play::showMark

set mainWin .jigsaw

wm withdraw .
toplevel $mainWin
jigsaw-main::setToplevel $mainWin

wm title $mainWin "Jigsaw Puzzler"
wm protocol $mainWin WM_DELETE_WINDOW [list jigsaw-main::closeDown $mainWin]

if { $::tcl_platform(os) eq "Darwin" } {
    # Add dummy menu for MacOS.
    set hMenu $mainWin.menufr
    menu $hMenu
    $mainWin configure -menu $hMenu
}

set midFr [frame $mainWin.midFr]

# Create a canvas
set c [jigsaw-main::buildCanvas $midFr]
jigsaw-main::setCanvas $c
bind $c <Configure> {jigsaw-main::centraliseItems %W}

set toolFr [jigsaw-main::buildToolbar $mainWin $c]

grid $toolFr -row 0 -column 0 -sticky news
grid $midFr  -row 1 -column 0 -sticky news
grid rowconfigure    $mainWin 1 -weight 1
grid columnconfigure $mainWin 0 -weight 1

# Setup scrollregion to include everything on the canvas
jigsaw-main::updateCanvasScrollregion $c

# Place image in the centre of the canvas
update 
jigsaw-main::centraliseItems $c

set optPuzFile ""
set curArg 0
while { $curArg < $argc } {
    set curParam [lindex $argv $curArg]
    if { [string compare -length 1 $curParam "-"]  == 0 || \
         [string compare -length 2 $curParam "--"] == 0 } {
        set curOpt [string tolower [string trimleft $curParam "-"]]
        if { $curOpt eq "help" } {
            PrintUsage $argv0
            exit 0
        } elseif { $curOpt eq "play" } {
            jigsaw-main::setPlayMode
        } elseif { $curOpt eq "fullscreen" } {
            jigsaw-main::setFullscreen $mainWin
        }
    } else {
        set optPuzFile $curParam
    }
    incr curArg
}

if { $::tcl_platform(os) eq "Darwin" } {
    proc ::tk::mac::OpenDocument { args } {
        foreach param $args {
            if { [file exists $param] } {
                set optPuzFile $param
            }
        }
        jigsaw-main::openDirect [jigsaw-main::getToplevel] [jigsaw-main::getCanvas] $optPuzFile
    }

    proc ::tk::mac::Quit {} {
        jigsaw-main::closeDown $::mainWin
    }
}


if { $optPuzFile ne "" && [file exists $optPuzFile] } {
    jigsaw-main::openDirect [jigsaw-main::getToplevel] [jigsaw-main::getCanvas] $optPuzFile
}
