# jfileio.tcl - read and write text to files
#
###############################################################################
#  Copyright 1992-2001 by Jay Sekora.  This file may be freely distributed,   #
#  modified or unmodified, for any purpose, provided that this copyright      #
#  notice is retained verbatim in all copies and no attempt is made to        #
#  obscure the authorship of this file.  If you distribute any modified       #
#  versions, I ask, but do not require, that you clearly mark any changes     #
#  you make as such and that you provide your users with instructions for     #
#  getting the original sources.                                              #
###############################################################################

package provide aq 0.1

# following has side-effect of making sure ::aq namespace is defined
namespace eval ::aq {
  namespace export {[a-z]*}
}

######################################################################
# write given text to a file
######################################################################

proc ::aq::write_file { filename text } {
  set file [open $filename w]
  puts -nonewline $file $text
  close $file
}

######################################################################
# return contents of file
######################################################################

proc ::aq::read_file { filename } {
  # not using -nocase because Tcl 8.0 doesn't support it
  if {[string match http://* $filename]} {
    return [::aq::read_file_http $filename]
  }
  if {[string match HTTP://* $filename]} {
    return [::aq::read_file_http $filename]
  }
  set file [open $filename r]
  set result [read $file]
  close $file
  
  return $result
}

proc ::aq::read_file_http { filename } {
  if {[catch {package require http 2.0}]} {
    error "HTTP library not available; can't read files via HTTP"
    return ""
  }
  set token [::http::geturl $filename]
  upvar #0 $token state
  if {[info exists state(error)]} {
    error $state(error)
    return ""
  }
  return $state(body)
}
