#!/usr/bin/wishx
#Run interest amortizations
set cnf(title)		"Mort Version 0.20"      ;#Sep 2004
#TODO:
#X- screen layout
#X- buttons to run one step, single payment, or to completion
#X- code to populate main window invoked for subsequent windows
#X- save/save file working
#X- load file from command line
#X- move clear_all routine into etext
#X- code to actually amortize something
#X- save geometry on exit
#- date pull-downs give -mod error
#- print function (part of etext?)
#- 

package require wylib
set cnf(appname)	mort
set cnf(natext)		{.mrt}			;#Native file extension

#Header fields:
set cnf(hdr) {\
    -f {princ		ent 10		{0 0}	{Amount:}	-just r -ini 0 -help {The amount of money being borrowed or amortized}}\
    -f {inter		ent 4		{0 1}	{Interest:}	-just r -ini $::cnf(defint) -help {The rate at which interest is calculated (10 = 10 percent)}}\
    -f {bdate		ent 12		{1 0}	{Begin:}	-spf dat -ini [date::date] -help {When interest will begin to accrue}}\
    -f {peri		pdm 10		{2 0}	{Period:}	-ini monthly -data {{week weekly} {month Monthly} {year Annually}} -help {How often payments will be made}}\
    -f {pmt		ent 8		{2 1}	{Payment:}	-just r -ini 0}\
}

#Preferences control array:
set cnf(pref) {\
  -f {defint	ent	{Default Interest:}	cnf(defint)	-def 10 -help {Default interest rate}}\
}

#Run the amortization
#------------------------------------------
proc run {w} {
    global cnf

    set res "Pmt Date             Amount   Interest  Principle    Balance\n"
    set bsecs [date::seconds [$w hdr get bdate]]	;#begin time
    set ysecs [expr 60 * 60 * 24 * 365]	;#seconds in a year
    
    set lsecs $bsecs			;#seconds at time of last payment
    set bal [rpn [$w hdr get princ] fix2]	;#running balance
    set pmt [rpn [$w hdr get pmt]]	;#payment size
    set intr [rpn [$w hdr get inter]]	;#interest rate
    set unit [$w hdr get peri]
    set atot 0.0			;#total payments
    set ptot 0.0			;#total principle
    set itot 0.0			;#total interest
    set i 1				;#payment counter
    while {$bal > 0} {

#FIXME units
        set secs [clock scan "$i month" -base $bsecs]	;#seconds at this payment
        set date [date::date $secs]		;#date of this payment
        set isecs [expr $secs - $lsecs]		;#seconds since last payment
#puts "isecs:$isecs ysecs:$ysecs rat:[rpn $isecs $ysecs /]"
        set int [rpn $bal $intr * 100 / $isecs * $ysecs / fix2]	;#interest accrued
        set payoff [rpn $bal $int +]
        if {$pmt > $payoff} {			;#this is the last payment
            set pmt $payoff
            set pr $bal				;#principle paid down
            set bal {0.00}
        } else {
            set pr [rpn $pmt $int -]		;#principle paid down
            set bal [rpn $bal $pr -]
        }
        if {$pr < 0} {dia::err "Negatively amortizing for interest: $int\npayment too small"; return}
        
#puts "date:$date int:$int pr:$pr bal:$bal"
        append res [format "%3d %-12s %10s %10s %10s %10s\n" $i $date $pmt $int $pr $bal]
        set atot [rpn $atot $pmt +]
        set itot [rpn $itot $int +]
        set ptot [rpn $ptot $pr +]
        set lsecs $secs			;#new 'seconds at last payment'
        incr i
    }
    append res [format "    Totals       %10s %10s %10s\n" $atot $itot $ptot]
    $w txt delete 0.0 end
    $w txt insert 0.0 $res
    $w txt see end
}

#Create the main window
#------------------------------------------
proc main_win {w} {
    global cnf
    top::add [eval mdew::mdew $w.hdr $cnf(hdr)]
    pack $w.hdr -side top -anchor w

    etext::etext $w.txt -menu [$w menu w] -header $w.hdr -natext $cnf(natext) -app $cnf(appname)
    pack $w.txt -side top -fill both -exp 1

    set m [$w menu w]
    $m tools mi sep -before 1
#    $m tools mi step -under 0 -s Step -help {Run amortization for one payment} -command "run $w 1" -before 1
    $m tools mi run -under 0 -s Run -help {Run amortization to the end} -command "run $w" -before 1
}

# main
#----------------------------------------------------
eval pref::init $cnf(pref)	;# -apply config_main
set w [top::top $cnf(appname) m main_win]

prargs $argv {
    -i	{m hdr set {inter %v}}
    -a	{m hdr set {princ %v}}
    -p	{m hdr set {pmt %v}}
    -r	{run $w}
} {{$w txt load {%v}}}

#m menu edit invoke prefs	;#for debugging
