/*
 ***************************************************************************
 *   	      		Writing the buffers to the file
 *
 * Data file is a binary file with default extension .IMP
 * It contains a header
 *	1 word			Polling frequency (in microsec)
 *	1 word			No of channels to poll
 *	n+2 bytes		Comment for the 1. channel
 *	n+2 bytes		Comment for the last channel polled
 * followed by data items (1 word). Two high bits of the data item word
 * specifies the channel while the other bits stand for the interval
 * from the previous to the current impulse on the channel.
 * All strings are written in the standard format as the two-byte length
 * field followed by the bytes of the string (the null byte included)
 *
 ***************************************************************************
 */

#include <dos.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>
#include "stdio.h"
#include "assert.h"
#define WRITING_BUFFERS
#include "impulses.h"
#include "filling.h"
#include "writing.h"
#include "telling.h"

/*
 *--------------------------------------------------------------------------
 *			Service writing routines
 */

#define write_item(item) \
	_write(Data_file_handle,(void *)&item,sizeof(item));

			/* Write a string in the standard form		*/
			/* two-byte length field followed by the	*/
			/* string body ('\0' terminator included)	*/
static void write_string(const char * sp)
{
  int len = strlen(sp)+1;		/* Account for '\0' char	*/
  _write(Data_file_handle,(void *)&len,sizeof(int));
  _write(Data_file_handle,(void *)sp,len);
}


/*
 *--------------------------------------------------------------------------
 *		  	   Writing buffer
 */

				/* Find out which buffer has been filled up*/
				/* and return the pointer to it		   */
static struct BUFFER far * get_filled_buffer()
{
  const struct BUFFER far * ip = Current_buffer;/* 1. buffer to checked	*/
  struct BUFFER far * bp = ip;			/* Current buffer checked*/
  while( bp->actual_length == 0 )
  {
    bp = bp->next;
    if( bp == ip )		      	/* Check to see whether we have returned to the buffer we started from*/
      return (void *)0;			/* All the buffers are empty	*/
  }
  return bp;
}

static void print_buffer(struct BUFFER far * bp)
{
  register int i;

  assure(bp != (void *)0,"Null pointer to the buffer to show");
  message("\n\nFilled buffer id '%c'",bp->id);
  message("\nBuffer size %u elements and %u of them has been filled",
	  bp->size,bp->actual_length);
  message("\nFirst 50 buffer elements are as follows\n");
  for(i=0; i<50; i++)
  {
    if( i % 10 == 0 )
      message("\n");
    message("%6u  ",(bp->data)[i]);
  }
}

/*
 *	Important note
 * The present program is to be compiled in the Tiny memory model.
 * It means all the pointer (except those explicitly specified by far)
 * are near pointer, i.e. they contain only offset portion of the PC address.
 * Pointers to the buffer has been explicitly declared to be far pointer,
 * i.e. they contain segment as well as offset portions of the address.
 * But all the standard functions (e.g. fwrite, write) in this memory
 * model can take the near pointer only. There are no way to pass them
 * the far pointer. That is why we are forced to call the DOS write service
 * (DOS interrupt 0x40, write to the device) and explicitly set
 * segment registers.
 *
 */

static void writing_buffer(struct BUFFER far * bp)
{
  register unsigned length_in_bytes;
  union REGS regs; struct SREGS sregs;
  int ret;

  assure(bp != (void *)0,"Null pointer to the buffer to write");
  assure(bp->actual_length <= bp->size,
	 "Buffer must have been corrupted");
  assure((length_in_bytes = bp->actual_length * sizeof(ELEMENT)) != 0,
	"Buffer to be written is actually empty");

   regs.h.ah = 0x40;               	/* write to the file 		*/
   regs.x.bx = Data_file_handle;
   regs.x.cx = length_in_bytes;
   regs.x.dx = FP_OFF(bp->data);	/* This is the way we pass	*/
   sregs.ds  = FP_SEG(bp->data);	/* the far pointer		*/
   ret = intdosx(&regs, &regs, &sregs);

   if( regs.x.cflag )
     _error("Dos Write service (0x40) detected an error %xh. \n\
     Please consult the DOS reference",ret);
   else if( ret != length_in_bytes )
     _error("Dos has failed writing the buffer. Hard disk must have been full!");
}

				/* Set the file name of the output file	*/
				/* and opens it. Returns the pointer	*/
				/* to the error message	if failed	*/
				/* Return 0 otherwise			*/
char *  set_output_file_name(const char *file_name)
{
  if( strlen(file_name)+strlen(Default_extension) >= sizeof(Data_file_name)-1 )
    return "Too long file name";
  strcpy(Data_file_name,file_name);
  if( strchr(Data_file_name,'.') == (char *)0 )
    strcat(Data_file_name,Default_extension);

  Data_file_handle = open(Data_file_name,O_WRONLY | O_CREAT | O_BINARY);
  if( Data_file_handle == -1 )
    return _strerror("Error opening data file");
  return (char *)0;
}

void init_writing_buffer()
{
  register int i;
  assure( Data_file_handle != 0,
	  "File hasn't been opened!");
  write_item(Polling_period);
  write_item(No_channels_polled);
  for(i=1; i<=No_channels_polled; i++)
     write_string(Comments_to_channels[i]);
}


void write_buffer()
{
  struct BUFFER far * bp;

  while( (bp = get_filled_buffer()) != (void *)0 )
  {
    Total_no_impulses += bp->actual_length;
    writing_buffer(bp);
    Status = 'N';
    bp->actual_length = 0;
  }
}

void complete_writing_buffer()
{
  push_current_buffer();
  write_buffer();
  _close(Data_file_handle);
}

