/* This file is part of Lcrzo.
*/

int lcrzo_ipc_close(lcrzo_ipc *pipc)
{ int ret;

  /*parameters verification*/
  if (pipc==NULL) return(LCRZO_ERR_PANULLPTR);

  /* send the ending message */
  if (pipc->openforwriting)
  { lcrzo_priv_ipc_writetlv(pipc, LCRZO_PRIV_IPCTYPE_MSGEND, NULL, 0);
  }

  /* close */
#if defined LCRZODEF_SYSTEM_Unix
  if (pipc->side==-1)
  { ret=close(pipc->readpipe[0]);
    if (ret==-1) return(LCRZO_ERR_FUCLOSE);
    ret=close(pipc->readpipe[1]);
    if (ret==-1) return(LCRZO_ERR_FUCLOSE);
    ret=close(pipc->writepipe[0]);
    if (ret==-1) return(LCRZO_ERR_FUCLOSE);
    ret=close(pipc->writepipe[1]);
    if (ret==-1) return(LCRZO_ERR_FUCLOSE);
  }
  else
  { if (pipc->openforreading)
    { ret=close(pipc->readpipe[pipc->side]);
      if (ret==-1) return(LCRZO_ERR_FUCLOSE);
      #if defined LCRZOTEST_HOOK_IPCSIDE
        if (lcrzotest_hook_ipcside==LCRZO_TRUE)
        { ret=close(pipc->readpipe[(pipc->side==1)?0:1]);
          if (ret==-1) return(LCRZO_ERR_FUCLOSE);
        }
      #endif
      pipc->openforreading=LCRZO_FALSE;
    }
    if (pipc->openforwriting)
    { ret=close(pipc->writepipe[pipc->side]);
      if (ret==-1) return(LCRZO_ERR_FUCLOSE);
      #if defined LCRZOTEST_HOOK_IPCSIDE
        if (lcrzotest_hook_ipcside==LCRZO_TRUE)
        { ret=close(pipc->writepipe[(pipc->side==1)?0:1]);
          if (ret==-1) return(LCRZO_ERR_FUCLOSE);
	}
      #endif
      pipc->openforwriting=LCRZO_FALSE;
    }
  }
#elif defined LCRZODEF_SYSTEM_Windows
  if (pipc->side==0)
  { ret=CloseHandle(pipc->readhandle[0]);
    if (!ret) return(LCRZO_ERR_FUCLOSEHANDLE);
    ret=CloseHandle(pipc->writehandle[0]);
    if (!ret) return(LCRZO_ERR_FUCLOSEHANDLE);
    ret=CloseHandle(pipc->readhandle[1]);
    if (!ret) return(LCRZO_ERR_FUCLOSEHANDLE);
    ret=CloseHandle(pipc->writehandle[1]);
    if (!ret) return(LCRZO_ERR_FUCLOSEHANDLE);
  }
  pipc->openforreading=LCRZO_FALSE;
  pipc->openforwriting=LCRZO_FALSE;
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  /* free data */
  if (pipc->storeddata==NULL && pipc->storeddatasize) 
    return(LCRZO_ERR_PANULLPTRSIZE);
  if (pipc->storeddatasize)
  { lcrzo_er(lcrzo_data_free(pipc->storeddata));
    pipc->storeddata=NULL;
    pipc->storeddatasize=0;
  }

  pipc->dataend=LCRZO_TRUE;
  return(LCRZO_ERR_OK);
}

