#!@TCLSH@


if {[llength $argv] != 2} {
  puts "Usage: mkbook <infile> <outfile>"
  exit
}

if {[file exists [lindex $argv 0]] == 0} {
  puts "File '[lindex $argv 0]' does not exist!"
  exit
}

exec pstops "4:-3L@0.7(21cm,0)+0L@0.7(21cm,14.85cm),1R@0.7(0,29.7cm)+-2R@0.7(0,14.85cm)" [lindex $argv 0] /tmp/tmp.ps 2>/tmp/tmp.txt

set output [exec cat /tmp/tmp.txt]

regexp {[ ][0-9]+[ ]} $output match
regsub -all {[ ]} $match "" match_val
set pages {}

for {set i 1} {$i <= $match_val} {incr i} {
  lappend pages $i
}


while {$pages != ""} {
  lappend page_list [lindex $pages 0]
  set pages [lreplace $pages 0 0]
  lappend page_list [lindex $pages 0]
  set pages [lreplace $pages 0 0]
  if {$pages != ""} {
    lappend page_list [lindex $pages [expr [llength $pages] - 1]]
    lappend page_list [lindex $pages [expr [llength $pages] - 2]]
    set pages [lreplace $pages [expr [llength $pages] - 2] [expr [llength $pages] -1 ]]
  }
}

set command ""

for {set i 0} {$i < [llength $page_list]} {incr i} {
  if {$i != 0} {
    set command [append command ","]
  }
  set command [append command [lindex $page_list $i]]
}


exec psselect -q -p$command /tmp/tmp.ps /tmp/tmp1.ps

exec pstops "4:0,1,2U(21cm,29.7cm),3U(21cm,29.7cm)" /tmp/tmp1.ps [lindex $argv 1] 2>/dev/null

exec rm -f /tmp/tmp.txt /tmp/tmp.ps /tmp/tmp1.ps


