#!/www/bin/mhc
;;; b64decode.mhc: -*- Meta-HTML -*-  DESCRIPTIVE TEXT.
;;;
;;; Copyright (c) 1999 Brian J. Fox
;;; Author: Brian J. Fox (bfox@ai.mit.edu) Sun Apr 18 11:32:48 1999.
<set-var mhc::explicit-output-only = true>

<defun --help-handler arg>
  <if <get-var-once arg>
      <mhc::print "b64decode: unknown flag: `<get-var-once arg>'\n">>

  <mhc::print
   "Usage: b64decode [--output=OUTPUT-FILENAME] FILE...

  Decode the specified file(s) placing the output into OUTPUT-FILENAME.
  If OUTPUT-FILENAME is not specified, the input filename is used, with
  \".decoded\" appended to it.
  ">

  <if <get-var-once arg>
      <mhc::exit 1>
    <mhc::exit 0>>
</defun>

<defun --output-handler arg>
  <set-var default::output-filename=<get-var-once arg>>
</defun>

<defun default-handler arg>
  <if <match <get-var-once arg> "^-">
      <--help-handler <get-var-once arg>>
    <array-append <get-var-once arg> default::input-filenames>>
</defun>

<mhc::parse-program-arguments>

<if <not <get-var-once input-filenames>>
    <--help-handler>>

<if <not <get-var-once output-filename>>
    <set-var output-filename = <get-var-once input-filenames[0]>.decoded>>

<foreach file input-filenames>
  <set-var read? = <dir::read-file <get-var-once file> contents>>
  <when <get-var-once read?>>
    <coerce-var contents type=string>
    <base64decode <get-var-once contents> output>
    <set-var written?=<dir::write-file <get-var-once output-filename> output>>
  </when>
  <if <not <get-var-once read?>>
      <concat
       <mhc::print "b64decode: Couldn't read the file <get-var-once file>!\n">
       <--help-handler>>
    <if <not <get-var-once written?>>
	<concat
	 <mhc::print "b64decode: Couldn't write the output file <get-var-once output-filename>!\n">
	 <--help-handler>>>>
</foreach>
<mhc::exit 0>

    