#include <stdlib.h>
#include <io.h>
#include <fcntl.h>

#define VIEW "v" /* default */

void printdvi(int input, char *cmd)
{
  char buf[1024], out[256], *tmp;
  int len, output, bytes;

  tmp = getenv("TMP");

  strcpy(out, tmp ? tmp : "\\");
  len = strlen(out);
  if ( out[len - 1] == '/' || out[len - 1] == '\\' )
    out[len - 1] = 0;
  strcat(out, "\\d_XXXXXX");
  mktemp(out);
  strcat(out, "."); /* fix emTeX dvi driver bug: name without extension */

  if ( (output = open(out, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666)) == -1 )
    return;

  while ( (bytes = read(input, buf, sizeof(buf))) > 0 )
    if ( write(output, buf, bytes) == -1 )
      break;
    
  close(output);

  if ( strstr(cmd, "%s") )
    sprintf(buf, cmd, out);
  else
  {
    strcpy(buf, cmd);
    strcat(buf, " ");
    strcat(buf, out);
  }

  system(buf);

  unlink(out);
}

void main(int argc, char **argv)
{
  char *cmd = getenv("DVI_PRINT_COMMAND");
  char buf[1024];
  int arg, file;

  cmd = cmd ? cmd : VIEW;

  if ( argc == 1 )
    if ( isatty(0) )
    {
      printf("\nUsage: %s [file ...]"
             "\n   or: command | %s\n", argv[0], argv[0]);
      exit(1);
    }
    else
    {
      setmode(0, O_BINARY);
      printdvi(0, cmd);
    }
  else
    for ( arg = 1; arg < argc; arg++ )
      if ( access(argv[arg], 0) == 0 )
      {
	if ( strstr(cmd, "%s") )
	  sprintf(buf, cmd, argv[arg]);
	else
	{
	  strcpy(buf, cmd);
	  strcat(buf, " ");
	  strcat(buf, argv[arg]);
	}

	system(buf);
      }
  
  exit(0);
}
