#!/usr/bin/tclsh
#if this script does not work, CHANGE the line above to the path to tclsh
#(if you don't know what path that is, try 'whereis tclsh')

puts "fp2db Infobot factpack converter"
puts "by Mac-arena the Bored Zo, gratis under GPL"
puts "(see LICENSE file that you should have gotten in this package)"
puts "---"

set keepGoing 1
while $keepGoing {
        puts "Enter a path to an Infobot(pl) factpack:"
        gets stdin fpname
		if {$fpname == ""} {
			return "(Quit)"
		}
		
        set fpfile [open $fpname r]
        set fptext [read -nonewline $fpfile]
		regsub -all {^#[^\n\r]+} $fptext {} dbtext
		regsub -all {[\n\r]#[^\n\r]+} $dbtext {} dbtext
        regsub -all {([^\n\r]+) => ([^\n\r]+)} $dbtext {[list {\1}] [list {\2}]} dbtext
        set dbtext [subst -nobackslashes -novariables $dbtext]
        close $fpfile

        if {
                ! [regsub {^(.+)\.fact$} $fpname {\1.db} dbname]
        } {
                set dbname "$fpname.db"
        }

        if [file exists $dbname] {
                puts "$dbname ALREADY EXISTS!! REALLY replace? \[yN\]"
                set confirm [read stdin 1]
                if [regexp {^[Yy]$} $confirm] {
                        set dbfile [open $dbname w]
                        puts -nonewline $dbfile $dbtext
                        close $dbfile
		    puts "Succeeded conversion of $fpname to $dbname."
                } else {
                        puts "Skipped $dbname."
                }
        } else {
                set dbfile [open $dbname w]
                puts -nonewline $dbfile $dbtext
                close $dbfile
	    puts "Succeeded conversion of $fpname to $dbname."
        }
}