/* $Id: b64test.c,v 1.4 2002/06/23 20:28:31 richdawe Exp $ */

/*
 * b64test.c - Test program for pakke's Base64 code
 * Copyright (C) 2000-2002 by Richard Dawe
 */

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

#include "base64.h"

#define BUFSIZE	32768
#define NUM_TESTS 10

unsigned char buf[BUFSIZE];
unsigned char e_buf[BUFSIZE * 2];
unsigned char d_buf[BUFSIZE];

/* --------
 * - main -
 * -------- */

int
main (int argc, char *argv[])
{
  int i, j;
  int quiet = 0;
  ssize_t ret;
  size_t e_size, d_size;

  for (i = 1; i < argc; i++) {
    /* Quiet operation, for automatic testing. */
    if (   (strcmp(argv[i], "--quiet") == 0)
	|| (strcmp(argv[i], "-q") == 0))
      quiet = 1;
  }

  /* Perform the test a number of times. */
  for (i = 0; i < NUM_TESTS; i++) {
    if (!quiet)
      printf("Test %i\n", i);
		
    /* Generate some random data to encode. */
    for (j = 0; j < sizeof(buf); j++) {
      buf[j] = (unsigned char) random();
    }

    /* Encode all the data, but check padding by not including
     * part of the 4-byte range at the end. */
    for (j = BUFSIZE - 4; j <= BUFSIZE; j++) {	
      /* Go for broke - encode and then decode. */
      e_size = sizeof(e_buf);
      ret = base64_encode(buf, j, e_buf, &e_size);
      if (ret < 0) {
	if (!quiet)
	  printf("Base64 encoding failed\n");
	return(EXIT_FAILURE);
      }
      /*printf("Base64 encoding returned %i\n", ret);*/

      d_size = sizeof(d_buf);
      ret = base64_decode(e_buf, e_size, d_buf, &d_size);
      if (ret < 0) {
	if (!quiet)
	  printf("Base64 decoding failed\n");
	return(EXIT_FAILURE);
      }			
      /*printf("Base64 decoding returned %i\n", ret);*/

      /* Compare the memory. */
      if (!quiet) {
	printf("Original size = %i, "
	       "encoded size = %li, "
	       "decoded size = %li\n",
	       j, e_size, d_size);
      }
			
      if (memcmp(buf, d_buf, j) == 0) {
	if (!quiet) {
	  printf("Encoding-decoding cycle SUCCESSFUL - "
		 "identical data before & after\n");
	}
      } else {
	if (!quiet) {
	  printf("Encoding-decoding cycle FAILED - "
		 "different data before & after\n");
	}
	break;
      }
    }
  }
	
  return(EXIT_SUCCESS);
}
