/*	$Id: libuu.c,v 1.1.1.1.4.2 2002/02/27 17:41:10 pwessel Exp $
 *
 *      Copyright (c) 1999-2002 by P. Wessel
 *      See COPYING file for copying and redistribution conditions.
 *
 *      This program 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; version 2 of the License.
 *
 *      This program 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.
 *
 *      Contact info: www.soest.hawaii.edu/wessel
 *--------------------------------------------------------------------*/
/*
 *      Include file for programs using libuu.a to do Unix-style
 *	uuencode and uudecode from within programs.  Currently
 *	the file permission mode is ignored and set to 644.
 *	See libuu.c for how to use the functions in your code.
 *
 * Author:    Paul Wessel, SOEST, U. of Hawaii
 * Version:   1.0
 * Date:      01-MAR-2000
 *
 * libuu.c: An i/o library based on uuencode and uudecode
 *
 * All that was done was to combine uuencode.c and uudecode.c
 * and replace the implicit stdin and stdout with filepointers
 * and make two functions:
 *
 * int uu_encoder (FILE *in, FILE *out, char file[], char tag[], const char *prefix)
 *	in:		Pointer to stream from which to read data to be encoded
 *	out:		Pointer to stream to write encoded data
 *	file:		Where to write the encoded file when out = NULL.  3 choices:
 *			1) NULL: Write to stdout
 *			2) file: write to file with this name
 *			3) file[0] = 0: Make temporary file name
 *			   and return name in file
 *	tag:		what uuencode calls decode-pathname: it is the
 *			name of the file that uudecode will save the
 *			decoded file to.
 *	prefix:		Leading text string (if not NULL) to begin
 *			every record before the uu code is written
 *
 * int uu_decoder (FILE *in, FILE *out, char file[], char tag[], const char *prefix)
 *	in:		Pointer to stream from which to read data to be decoded
 *	out:		Pointer to stream to write decoded data
 *	file:		Where to write the restored file when out = NULL.  3 choices:
 *			1) NULL: Write to stdout
 *			2) file: write to file with this name
 *			3) file[0] = 0: Make temporary file name
 *			   and return name in file
 *	tag:		what uuencode calls decode-pathname: it is the
 *			name of the file that uudecode will save the
 *			decoded file to.
 *	prefix:		Leading text string (if not NULL) that begins
 *			every record before the uu code is read
 *
 * The functions take the same kind of arguments to that it is easy to
 * use a pointer to the functions instead.
 * WIN32:  The in file pointer passed to uu_encoder and the out file pointer
 * passed to uu_decoder must refer to files opened in binary mode since we do
 * not know which files are binary or which are ascii.  We must thus deal
 * explicitly with crap like CR/LF.
 * The following is a plain program driver that uses these functions:
 * (Note this driver does not properly deal with CR/LF for DOS).
 *
 *------------------------------------------------------------------
/* This main is an example of how to use libuu in a program */
/*
 * #include <stdio.h>
 * #include "uu.h"
 * 
 * main (int argc, char **argv) {
 * 	int i, way = UU_ENCODE, help = 0;
 * 	char tag[BUFSIZ], *prefix;
 * 	FILE *fp = stdin;
 * 
 * 	prefix = NULL;
 * 	tag[0] = 0;
 * 	
 * 	for (i = 1; i < argc; i++) {
 * 		if (argv[i][0] == '-') {
 * 			switch (argv[i][1]) {
 * 				case 'd':
 * 					way = UU_DECODE;
 * 					break;
 * 				case 'h':
 * 					help = 1;
 * 					break;
 * 				case 't':
 * 					strcpy (tag, &argv[i][2]);
 * 					break;
 * 				case 'p':
 * 					prefix = &argv[i][2];
 * 					break;
 * 				default:
 * 					fprintf (stderr, "uu: Unknown option %s\n", argv[i]);
 * 					exit (1);
 * 			}
 * 		}
 * 		else if ((fp = fopen (argv[i], "r")) == NULL) {
 * 			fprintf (stderr, "uu: Cannot open file %s\n", argv[i]);
 * 			exit (1);
 * 		}
 * 	}
 * 	
 * 	if (help) {
 * 		fprintf (stderr, "usage: uu [file] [-d] [-t<tab>] [-p<prefix>]\n");
 * 		fprintf (stderr, "	-d  decode [Default is encode]\n");
 * 		fprintf (stderr, "	-h  give help\n");
 * 		fprintf (stderr, "	-t  set tag [NONE]\n");
 * 		fprintf (stderr, "	-p  set prefix [NONE]\n");
 * 		exit (1);
 * 	}
 * 	
 * 	if (uu_io[way] (fp, stdout, NULL, tag, prefix)) {
 * 		fprintf (stderr, "uu: Error from libuu\n");
 * 		return (1);
 * 	}
 * }
 */
 
/*------------------------------------------------------------------
 *
 * The original Copyright for uuencode and uudecode follows below.
 */
 
/* 
   Copyright (C) 1994, 1995 Free Software Foundation, Inc.

   This product 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 product 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 this product; see the file COPYING.  If not, write to
   the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
   02111-1307, USA.  */

/* Copyright (c) 1983 Regents of the University of California.
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
   3. All advertising materials mentioning features or use of this software
      must display the following acknowledgement:
	 This product includes software developed by the University of
	 California, Berkeley and its contributors.
   4. Neither the name of the University nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   SUCH DAMAGE.  */

/* Reworked to GNU style by Ian Lance Taylor, ian@airs.com, August 93.  */

#include <stdio.h>
#include <string.h>

#define LIBUU
#include "uu.h"

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#define fileno(stream) _fileno(stream)
#define setmode(fd,mode) _setmode(fd,mode)
#endif
#ifdef __EMX__  /* Start of OS/2 with EMX support */
#include <io.h>
#endif
#ifdef _WIN32
#include <fcntl.h>
#endif

/* Translation table for  standard uuencoding */
const char uu_std[64] =
{
  '`', '!', '"', '#', '$', '%', '&', '\'',
  '(', ')', '*', '+', ',', '-', '.', '/',
  '0', '1', '2', '3', '4', '5', '6', '7',
  '8', '9', ':', ';', '<', '=', '>', '?',
  '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
  'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  'X', 'Y', 'Z', '[', '\\', ']', '^', '_'
};

/* ENC is the basic 1 character encoding function to make a char printing.  */
#define ENC(Char) (uu_std[(Char) & 077])
/* Single character decode.  */
#define	DEC(Char) (((Char) - ' ') & 077)

int uu_encoder (FILE *in, FILE *out, char file[], char tag[], const char *prefix)
{
	register int ch, n, close = 0;
	register char *p, *tmp;
	char buf[80];

	if (!out) {
		if (file == NULL) {	/* use stdout */
			out = stdout;
		}
		else if (file[0] == 0) {	/* Make file name */
			tmp = tmpnam (NULL);
			if ((out = fopen (tmp, "w")) == NULL) return 2;
			strcpy (file, tmp);
			close = 1;
		}
		else {	/* Use specified file name */
			if ((out = fopen (file, "w")) == NULL) return 2;
			close = 1;
		}
	}
	
	if (prefix)
		fprintf (out, "%sbegin 644 %s\n", prefix, tag);
	else
		fprintf (out, "begin 644 %s\n", tag);
		
	while (1)
	{
		n = 0;
		do
		{
			register int m = fread (buf, 1, 45 - n, in);
			if (m == 0) break;
			n += m;
		}
		while (n < 45);

		if (n == 0) break;

		if (prefix) fprintf (out, "%s", prefix);
		if (fputc (ENC (n), out) == EOF) break;
			
		for (p = buf; n > 2; n -= 3, p += 3)
		{
			ch = *p >> 2;
			ch = ENC (ch);
			if (fputc (ch, out) == EOF) break;
			ch = ((*p << 4) & 060) | ((p[1] >> 4) & 017);
			ch = ENC (ch);
			if (fputc (ch, out) == EOF) break;
			ch = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03);
			ch = ENC (ch);
			if (fputc (ch, out) == EOF) break;
			ch = p[2] & 077;
			ch = ENC (ch);
			if (fputc (ch, out) == EOF) break;
		}

		if (n != 0) break;
		if (fputc ('\n', out) == EOF) break;
	}

	while (n != 0)
	{
		char c1 = *p;
		char c2 = (n == 1) ? 0 : p[1];

		ch = c1 >> 2;
		ch = ENC (ch);
		if (fputc (ch, out) == EOF) break;

		ch = ((c1 << 4) & 060) | ((c2 >> 4) & 017);
		ch = ENC (ch);
		if (fputc (ch, out) == EOF) break;

		if (n == 1)
			ch = ENC ('\0');
		else
		{
			ch = (c2 << 2) & 074;
			ch = ENC (ch);
		}
		if (fputc (ch, out) == EOF) break;
		ch = ENC ('\0');
		if (fputc (ch, out) == EOF) break;
		fputc ('\n', out);
		n = 0;	/* old code had break; which gave warnings */
	}

	if (ferror (in)) return 2;
	
	if (prefix) fprintf (out, "%s", prefix);
	fputc (ENC ('\0'), out);
	fputc ('\n', out);
	if (prefix) fprintf (out, "%s", prefix);
	fprintf (out, "end\n");
	
	if (close) fclose (out);
	return (0);
}

int uu_decoder (FILE *in, FILE *out, char file[], char tag[], const char *prefix)
{
	int np, offset = 0, close = 0;
	char buf[2 * BUFSIZ], match[BUFSIZ], *tmp;

	/* Search for header line.  */

	if (prefix) {
		offset = strlen (prefix);
		sprintf (match, "%sbegin", prefix);
	}
	else
		strcpy (match, "begin");
	np = 5 + offset;	/* 5 = strlen("begin") */
	
	while (1)
	{
		if (fgets (buf, sizeof (buf), in) == NULL) return 1;
		if (strncmp (buf, match, np) == 0) break;
	}

	/* Get file name */
	
	sscanf (buf, "%*s %*s %s", tag);
	if (!out) {	/* No pointer provided, must set it base on other information */
		if (file == NULL) {
			out = stdout;
#ifdef _WIN32		/* Reset stdout mode to BIN */
			setmode (fileno (out), _O_BINARY);
#elif WIN32
			_fsetmode (out, "b");
#endif
		}
		else if (file[0] == 0) {
			tmp = tmpnam (NULL);
			if ((out = fopen (tmp, "wb")) == NULL) return 2;
			strcpy (file, tmp);
			close = 1;
		}
		else {
			if ((out = fopen (tag, "wb")) == NULL) return 2;
			strcpy (file, tag);
			close = 1;
		}
	}
	
	if (prefix)
		sprintf (match, "%send\n", prefix);
	else
		strcpy (match, "end\n");

	/* For each input line:  */
	
	while (1)
	{
		int n;
		char *p;

		if (fgets (buf, sizeof(buf), in) == NULL)
			return 3;
		if (!strcmp (buf, match))
			break;

		p = &buf[offset];

		/* N is used to avoid writing out all the characters at the end of the file.  */

		n = DEC (*p);
		for (++p; n > 0; p += 4, n -= 3)
		{
			int ch;

			if (n >= 3)
			{
				ch = DEC (p[0]) << 2 | DEC (p[1]) >> 4;
				fputc (ch, out);
				ch = DEC (p[1]) << 4 | DEC (p[2]) >> 2;
				fputc (ch, out);
				ch = DEC (p[2]) << 6 | DEC (p[3]);
				fputc (ch, out);
			}
			else
			{
				if (n >= 1)
				{
					ch = DEC (p[0]) << 2 | DEC (p[1]) >> 4;
					fputc (ch, out);
				}
				if (n >= 2)
				{
					ch = DEC (p[1]) << 4 | DEC (p[2]) >> 2;
					fputc (ch, out);
				}
			}
		}
	}

	if (close) fclose (out);
	
	return 0;
}
