/* **********************************************************************
 * *                                                                    *
 * *                                                                    *
 * *                                                                    *
 * **********************************************************************
 * File: utils/tdwr/global_memory_attach.c
 *
 *                        COPYRIGHT (c) 2004  BY
 *          SIGMET INCORPORATED, WESTFORD MASSACHUSETTS, U.S.A.
 * 
 * THIS SOFTWARE IS FURNISHED UNDER A LICENSE AND MAY BE USED AND  COPIED
 * ONLY  IN  ACCORDANCE WITH  THE  TERMS  OF  SUCH  LICENSE  AND WITH THE
 * INCLUSION OF THE ABOVE COPYRIGHT NOTICE.  THIS SOFTWARE  OR  ANY OTHER
 * COPIES  THEREOF MAY NOT BE PROVIDED OR OTHERWISE MADE AVAILABLE TO ANY
 * OTHER PERSON.  NO TITLE TO AND OWNERSHIP OF  THE  SOFTWARE  IS  HEREBY
 * TRANSFERED.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>

#include "sigtypes.h"
#include "user_lib.h"
#include "tdwr_interface.h"


void global_memory_attach(void)
{
  long global_memory_id;                     /* Shared mem ID  */
  char log_str[200];

  global_memory_id = shmget( 200, sizeof(union tdwr_buf) * 300, 0777|IPC_CREAT);
  if (global_memory_id < 0)
  {
    sprintf(log_str, "Failure to attach to shared memory - 200!\n");
    Lprintf(log_str);
    exit(EXIT_FAILURE);
  }
  dwell_p = (union tdwr_buf *)shmat( global_memory_id, 0, 0);

  global_memory_id = shmget( 201, sizeof(struct dwell_table), 0777|IPC_CREAT);
  if (global_memory_id < 0)
  {
    sprintf(log_str, "Failure to attach to shared memory - 201!\n");
    Lprintf(log_str);
    exit(EXIT_FAILURE);
  }
  dwell_table = (struct dwell_table *)shmat( global_memory_id, 0, 0);
}

void Lprintf(const char *log_str_a)
{
  struct full_time_spec Time;
  char sTimeBuf[TIMENAME_SIZE];
  if (!logging) return;

  GetTimeFull( &Time, TIME_FLG_LOCAL );

  shhmmssddmonyyyy_r( &Time.Ymds, sTimeBuf );
  fprintf(log_file, "%s %s: %s\n", sTimeBuf, Time.sRecordTZName, log_str_a);
  fflush(log_file);
  return;
}

/* ======================================================================
 * Function to print signaled errors to the loging file or terminal.
 */
MESSAGE SignalHandler
(MESSAGE iStatus_a,
 UINT4 iCount_a,
 const UINT4 iSigArgs_a[] )
{
  char sMessage[170];

  strncpy( sMessage, message_to_text( iStatus_a, iCount_a, iSigArgs_a ), 165 );
  sMessage[165]=0;

  Lprintf( sMessage );
  return(SS_NORMAL);
}
