/*-------------- Telecommunications & Signal Processing Lab ---------------
                             McGill University

Routine:
  int AFrdHtext (FILE *fp, int Size, const char Ident[], struct AF_info *Hinfo,
                 int Align)

Purpose:
  Read text and append as a record in an AFsp information structure

Description:
  This routine reads text from a file.  This text is prefixed by an
  identification string and placed as a record into an AFsp information
  structure.  The input string is considered to be terminated by a null
  character.  Trailing white space is removed.  If the result is non-empty, the
  text string is prefixed by the given identification for the field.  This
  record is added to the end of any existing records in the AFsp information
  structure.

Parameters:
  <-  int AFrdHtext
      Number of characters read (including any skipped characters)
   -> int Size
      Number of characters in the text string
   -> const char Ident[]
      Identification string to be prefixed to the text
  <-> struct AF_info *Hinfo
      AFsp information structure
   -> int Align
      Alignment requirement.  If Size is not a multiple of Align, file data
      up to the next multiple of Align is skipped, leaving the file positioned
      at that point.

Author / revision:
  P. Kabal  Copyright (C) 1998
  $Revision: 1.4 $  $Date: 1998/06/19 18:53:13 $

-------------------------------------------------------------------------*/

static char rcsid[] = "$Id: AFrdHtext.c 1.4 1998/06/19 libtsp-v3r0 $";

#include <ctype.h>
#include <string.h>

#include <libtsp/AFheader.h>
#include <libtsp/AFpar.h>

#define ICEILV(n,m)	(((n) + ((m) - 1)) / (m))	/* int n,m >= 0 */
#define RNDUPV(n,m)	((m) * ICEILV (n, m))		/* Round up */


int
AFrdHtext (fp, Size, Ident, Hinfo, Align)

     FILE *fp;
     int Size;
     const char Ident[];
     struct AF_info *Hinfo;
     int Align;

{
  int offs, N, Ni, nc;
  char *p, *q;

  N = Hinfo->N;
  p = &Hinfo->Info[N];
  offs = 0;

  /* Create information records with keywords and values */
  Ni = strlen (Ident);
  if (N + Ni + Size + 1 <= AF_MAXINFO) {
    /* Copy the Ident string */
    strcpy (&p[0], Ident);
    nc = Ni;

    /* Read the text string */
    offs += RHEAD_SN (fp, &p[nc], Size);
    nc += Size;
    p[nc] = '\0';	/* Add a null */
    nc = strlen (p);

    /* Strip trailing white space (and ~0 characters) */
    for (q = p+(nc-1); nc > 0 ; --nc, --q) {
      if (! isspace ((int)(*q)) && *q != '\377')
	break;
    }
    p[nc] = '\0';

    /* If the text is zero length, ignore it and the Ident string */
    if (nc > Ni)
      Hinfo->N = N + nc + 1;	/* Include the null char in the count */

    /* If the text is zero length, ignore it and the Ident string */
    nc = strlen (p) + 1;
    if (nc > Ni + 1)
      Hinfo->N = N + nc;
  }
  offs += RSKIP (fp, RNDUPV (Size, Align) - offs);

  return offs;
}
