#!/usr/bin/env tclsh
# slcread: convert a Sokoban levelset in the (XML-based) SLC format
# into the plaintext format readable by BOXcl, depends on TclXML only
# Usage: tclsh slcread.tcl input.scl > output.txt
# Created by Luxferre in 2024, released into public domain

package require xml

set levelsetfile ""
if {$argc > 0} { # get the level set file name
  set levelsetfile [lindex $argv 0]
} else {
  puts "Missing input file!"
  exit 1
}

set fp [open $levelsetfile r]
fconfigure $fp -encoding utf-8 -translation auto
set fdata [read $fp]
close $fp

set dataout 0
set xtitle 0

proc edata {name attlist args} {
  global dataout xtitle
  if {$name eq "Title"} {set xtitle 1}
  if {$name eq "LevelCollection"} {
    puts "Author: [dict get $attlist Copyright]"
  }
  if {$name eq "Level"} {
    puts "\nTitle: [dict get $attlist Id]"
  }
  if {$name eq "L"} {
    set dataout 1
  }
}

proc edataend {name args} {
  global dataout
  if {$name eq "L"} {
    set dataout 0
  }
}

proc cdata {data args} {
  global dataout xtitle
  if {$dataout eq 1} {
    puts $data
  }
  if {$xtitle eq 1} {
    puts "Title: $data"
    set xtitle 0
  }
}

set parser [::xml::parser -characterdatacommand cdata -elementstartcommand edata -elementendcommand edataend]
$parser parse $fdata
puts ""
