/*TITLE radix40 to ascii conversion */
/****keyword-flag*** "%v %f %n" */
/* "7 13-Mar-93,8:29:50 RADASC.C" */

#include <stdio.h>
#include <string.h>
#include "radix40.h"


char legal_chars[40] = " ,-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

unsigned weights[3] = {1600, 40, 1};

int radix40_to_ascii(unsigned char *ascii_data, Radix40 *radix40_data, int max_chars)
/* this routine converts a radix 40 character string */
/* to ascii representation.  Trailing blanks will be deleted. */
{
	int i;
	int ascii_length;
	int new_ascii_length;
	int words_to_convert;
	int cycle;
	unsigned current_word_index;
	unsigned current_word;
	unsigned current_char;

	ascii_length = max_chars;

	words_to_convert = ascii_length / 3;
	if (ascii_length % 3 != 0)
		words_to_convert ++;

	for (i = 0; i < max_chars + 1; i ++)
		ascii_data[i] = 0; /* this nulls out the output string */

	current_word_index = -1;
	cycle = 0;
	for (i = 0; i < ascii_length; i ++)
		{
		if (cycle == 0)
			{
			current_word_index ++;
			current_word = radix40_data[current_word_index];
			}
		current_char = current_word / weights[cycle];
		current_word -= current_char * weights[cycle];
		
		ascii_data[i] = legal_chars[current_char];
		cycle = (cycle + 1) % 3;
		}

	new_ascii_length = strlen((char *)ascii_data);
	for (i = new_ascii_length - 1; i >= 0; i --)
		{
		if (ascii_data[i] != ' ')
			break;
		ascii_data[i] = 0;
		}

	return(S_OKAY);
}




