# cp init_orig.tcl init.tcl
# bzip2 init.tcl

load ./libbztclLite.so

#
# Check short data
#

# This compresses to the same size it starts as.
# stuff smaller than this shouldn't be compressed.

set str {This is a simple little test, 
With few lines, and no more sense.
It's not better than the rest,
Which is really no sincere defense.
}

# Check compress/uncompress

set comp [bzLite compress $str]
puts "NOT AN ERROR: ORIG LEN: [string length $str] COMPRESSED LEN: [string length $comp]"
set uncomp [bzLite uncompress $comp]
if {![string equal $uncomp $str]} {
  puts "FAILED TO MATCH COMPRESSED AND UNCOMPRESSED:"
  puts "ORIG: \n$str"
  puts "UNCOMP: \n$uncomp"
}

# Check writeFile

bzLite writeFile test.bz2 $str
catch {file delete test}
exec bunzip2 test.bz2
set if [open test r]
set d [read $if]
close $if
if {![string equal $d $str]} {
  puts "FAILED TO bunzip2 a file written with writeFile"
}

# LARGER data tests - the internal buffer is 10 K,
#  these test confirm that the do stuff, copy buffer, do more stuff
#  sections of the C code are working right.

# Check readFile
set d [bzLite readFile "./init.tcl.bz2"]

set of [open init3.txt w]
puts -nonewline $of $d
close $of
if {[catch {exec diff init3.txt init_orig.tcl}]} {
  puts "FAILED TO get expected data with readFile"
  exec tkdiff init3.txt init_orig.tcl
}

# Read data and test compress

set if [open ./init.tcl.bz2 r]
fconfigure $if -translation {binary binary}
set d [read $if]
close $if

set d2 [bzLite uncompress $d]

if {[string length $d2] != 23250} {
  puts "Uncompressed data wrong length: [string length $d2] != 23250"
}

set of [open init3.txt w]
puts -nonewline $of $d2
close $of
if {[catch { exec diff init3.txt init_orig.tcl}]} {
  puts "FAILED TO match uncompressing data read from file"
  exec tkdiff init3.txt init_orig.tcl
}

# Check compress

set if [open init_orig.tcl r]
set d [read $if]
close $if

set d2 [bzLite compress $d]

set of [open init2.bz2 w]
fconfigure $of -translation {binary binary}
puts -nonewline $of $d2
close $of

catch {file delete init2}
exec bunzip2 init2.bz2

set if [open init2 r]
set d2 [read $if]
close $if

if {![string equal $d $d2]} {
  puts "FAILED TO MATCH original data and compress, write, bunzip2 data"
}

# Check writeFile

bzLite writeFile test.bz2 $d
catch {file delete test}
exec bunzip2 test.bz2
set if [open test r]
set d2 [read $if]
close $if
if {![string equal $d2 $d]} {
  puts "FAILED TO bunzip2 a file written with writeFile"
  exec tkdiff test init_orig.tcl
}

puts "If no error messages, it's working"
