/*---------------------------------------------------------------*/
/*   Copyright (c) 1992 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*-------------------------- ------------------------------------*/
/*
      @(#)BufMapData.c	1.2  (UCLA, IGPP) 20 Apr 1994 
*/
/*---------------------------------------------------------------
  BufMapData(int recptr) - internal function.
    Returns a pointer to an area of memory pointed to by a buffer
    record.  If the buffer item is in file store, the item is 
    bought into memory, an a pointer is return to that recors
    buffer.
 
  Return:
    char* an area of memory, should be changed to void* under ANSI C.
 
  Entry Requirements:
    RECPTR *recpt, which is returned by BufGetRecPtrOf().
 
  Development History:
    Began: 09/17/93 - Gilbert Hyatt.
    Edited:04/14/94 - Gilbert Hyatt 
      Now uses pipec.h as entry point into the library.
  ---------------------------------------------------------------*/
#include "pipec.h"

/* Main Function */
char*
BufMapData(recptr)
RECPTR *recptr;
{
  extern BUFFER_HEAD  _Rbuffer;
  extern char         *Rbuffer;
  int                 index, record, remain;
  RECPTR              *ptr;
  long                tell, place;

  /* if real memory send back address of data part */
  if (recptr->vmrecnum  == BufRealMem) return(recptr->data);

  /* if virtual memory, but in one of the pages in memory now send address of data */
  record = ((recptr->vmrecnum -1) / _Rbuffer.recs_per_page);
  remain = ((recptr->vmrecnum -1) % _Rbuffer.recs_per_page);
  if (record == _Rbuffer.num_inpage1) return((_Rbuffer.inpage1 + (remain * _Rbuffer.recl)));
  if (record == _Rbuffer.num_inpage2) return((_Rbuffer.inpage2 + (remain * _Rbuffer.recl)));
  if (record == _Rbuffer.num_outpage) return((_Rbuffer.outpage + (remain * _Rbuffer.recl)));


  /* if none of the above get the page into memory */
  if (memcmp(_Rbuffer.inpage2, _Rbuffer.inpage2_bak, _Rbuffer.pagesize) != 0) {
    fseek(_Rbuffer.vmfilename, (long)(_Rbuffer.num_inpage2 * _Rbuffer.pagesize), 0);
    fwrite(_Rbuffer.inpage2, _Rbuffer.pagesize, 1, _Rbuffer.vmfilename);
  } /* end of if */
  memcpy(_Rbuffer.inpage2,     _Rbuffer.inpage1,     _Rbuffer.pagesize);
  memcpy(_Rbuffer.inpage2_bak, _Rbuffer.inpage1_bak, _Rbuffer.pagesize);
  _Rbuffer.num_inpage2 = _Rbuffer.num_inpage1;

  fseek(_Rbuffer.vmfilename, (long)(record * _Rbuffer.pagesize), 0);
  fread(_Rbuffer.inpage1,  _Rbuffer.pagesize, 1, _Rbuffer.vmfilename);
  memcpy(_Rbuffer.inpage1_bak, _Rbuffer.inpage1, _Rbuffer.pagesize);
  _Rbuffer.num_inpage1 = record;
  
  return((_Rbuffer.inpage1 + remain * _Rbuffer.recl));
}  /* end of BufMapData */




    






















