;;; tramp-uu.el --- uuencode in Lisp

;; Copyright (C) 2002  Free Software Foundation, Inc.

;; Author: Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE>
;; Keywords: comm, terminals

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;; 

;;; Code:

(defun tramp-append-to-buffer (buffer &rest characters)
  "Into BUFFER, insert CHARACTERS at end."
  (save-excursion
    (set-buffer buffer)
    (goto-char (point-max))
    (apply 'insert characters)))

(defun tramp-uuencode-region (start end &optional mode filename)
  "Convert the current region to UU encoding."
  (interactive "r")
  (let (bits
	(len 0)
	pos line-pos c1 c2 c3 c4
	(workbuf (get-buffer-create " *tramp-uu-work* ")))
    (save-excursion
      (set-buffer workbuf)
      (erase-buffer))
    (save-excursion
      (unless mode (setq mode "644"))
      (unless filename (setq filename "xxx"))
      (setq pos start)
      (setq bits 0)
      (while (< pos end)
	(when (> (char-after pos) 256)
	  (error "Invalid character %c at position %d" (char-after pos) pos))
	(setq bits (logior bits (char-after pos)))
	(incf len)
	(when (or (zerop (% len 3))
		  (>= pos end))
	  (setq c1 (lsh bits -18))
	  (setq c2 (lsh (logand bits #b111111000000000000)
			-12))
	  (setq c3 (lsh (logand bits #b111111000000)
			-6))
	  (setq c4 (logand bits #b111111))
	  (message "Found chars %o %o %o %o" c1 c2 c3 c4)
	  (tramp-append-to-buffer
	   workbuf
	   (+ 32 c1) (+ 32 c2) (+ 32 c3) (+ 32 c4))
	  (setq bits 0))
	(when (or (>= len 45) (>= pos end))
	  (save-excursion
	    (set-buffer workbuf)
	    (beginning-of-line)
	    (insert (+ 32 len))
	    (end-of-line)
	    (insert "\n")
	    (goto-char (point-max))
	    (setq len 0)))
	(setq bits (lsh bits 8))
	(incf pos))
      (set-buffer workbuf)
      (goto-char (point-min))
      (insert (format "begin %s %s\n" mode filename))
      (goto-char (point-max))
      (insert "`\nend\n"))
    (delete-region start end)
    (insert-buffer workbuf)))
	

(provide 'tramp-uu)
;;; tramp-uu.el ends here
