/*
 * This file is part of the OLH system.
 *
 *      Lucien Van Elsen
 *	MIT Project Athena
 *
 * Copyright (C) 1990 by the Massachusetts Institute of Technology.
 * For copying and distribution information, see the file "mit-copyright.h".
 *
 *	$Source: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/ascii/view.c,v $
 *	$Id: view.c,v 1.3 1995/02/06 05:02:09 nygren Exp $
 *	$Author: nygren $
 */

#ifndef lint
#ifndef SABER
static char *RCSid = "$Header: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/ascii/view.c,v 1.3 1995/02/06 05:02:09 nygren Exp $";
#endif
#endif

#include <sys/file.h>
#ifdef SYSV
#include <sys/fcntl.h>
#endif
#include "global.h"
#include "olh.h"
#include "help.h"

#if defined(__NetBSD__) || defined(__linux__)
#define _PATH_MORE "/usr/bin/more"
#endif

#ifndef _PATH_MORE
#define _PATH_MORE "/usr/ucb/more -d"
#endif

void
  invoke_item( number )
int number;
{
  Menu *m;
  MenuEntry *e;
  long code;
  
  m = menu[current_menu];
  
  e = nth_entry(m, number);
  if (is_menu(e))
    {
      code = menu_load(e, &m);
      if (code)
	{
	  com_err(program, code, "loading %s", field_value(e, FILE_LOCATION));
	}
      else
	{
	  add_to_menupath(e);
	  current_menu++;
	  menu[current_menu] = m;
	  menu_entry[current_menu] = e;
	  current[current_menu] = 0;
	  viewed[current_menu] = FALSE;
	  current_offset = selection = 0;
	  OLH_ui_update_menus();
	  update_instructions();
	}
    }
  else
    {
      wclear(scr_view);
      set_current_screen(SCR_VIEW);
      nocbreak();
      echo();
      code = viewdoc(e, TTY,NULL);
      if (code != 0) {
	if (code == ERR_MENU_NOVIEWER) {
	  display_file(NOVIEWER_TEXT);
	  wait_for_key(win_sugg_wait);
	}
	else
	  com_err(program,code,"viewing %s", field_value(e, FILE_LOCATION));
      }
      cbreak();
      noecho();
      paint_menu();
      set_current_screen(SCR_PRIM);
    }
}


int
  display_file( path )
char* path;
{
  char buf[1024];
  char *viewer;
  
  viewer = getenv("PAGER");
  if (viewer == NULL || *viewer == '\0')
    viewer = _PATH_MORE;
  sprintf(buf, "%s %s", viewer, path);
  return(system(buf));
}

int
  display_buffer( buffer )
char* buffer;
{
  char name[16];
  int fd, len, count;
  int status;
  
  strncpy(name,"/tmp/olh_XXXXXX",16);
  mktemp(name);
  if ((fd = open(name,O_WRONLY|O_CREAT|O_TRUNC,0664)) < 0) {
     fprintf(stderr,"Could not open file %s for writing");
     return FALSE;
  }
  len = strlen(buffer);
  count = 0;
  while ((count+=write(fd, &buffer[count], len-count) < len) &&
	 (count != -1));
  
  close(fd);
  
  if (count == -1)
    {
      status = FALSE;
    }
  else
    {
      status = display_file(name);
      unlink(name);
    }
  return status;
}
