/* ul utility, but fails to support -i.  */

#include <stdio.h>

extern char **argvec;

char *getenv();
char *tgetstr();

int do_os;
char *start;
char *stop;
char *termtype;
char tcp_buf[1024];
char cap_buf[1024];

main (ac, av)
     int ac;
     char **av;
{
  char c;
  char d;
  int in_under;
  int is_under;

  if (strncmp (av[1], "-t", 2) == 0)
    {
      termtype = av[1] + 2;
      ac --;
      av ++;
    }
  else
    {
      termtype = getenv ("TERM");
      if (termtype == 0)
	{
	  termtype = "dumb";
	}
    }
  switch (tgetent (tcp_buf, termtype))
    {
    case -1:
      fprintf (stderr, "%s: cannot open termcap\n", argvec[0]);
      exit (1);
      break;

    case 0:
      strcpy (tcp_buf, "dumb:os:");
      break;
    }
  if (tgetflag ("os") || tgetflag ("ul"))
    {
      do_os = 1;
    }
  else
    {
      char *cp;
      do_os = 0;
      cp = cap_buf;
      start = tgetstr ("us", &cp);
      stop = tgetstr ("ue", &cp);
      if ((start == 0) || (stop == 0))
	{
	  start = tgetstr ("so", &cp);
	  stop = tgetstr ("se", &cp);
	  if ((start == 0) || (stop == 0))
	    {
	      start = "";
	      stop = "";
	    }
	}
    }
  in_under = 0;
  while (1)
    {
      c = getchar ();
      if (feof (stdin))
	{
	  break;
	}
      is_under = 0;
      if (c == '_')
	{
	  d = getchar ();
	  if (d == '\b')
	    {
	      c = getchar ();
	      is_under = 1;
	    }
	  else
	    {
	      ungetc (d, stdin);
	    }
	}
      if (is_under != in_under)
	{
	  printf ("%s", is_under?start:stop);
	  in_under = is_under;
	}
      putchar (c);
    }
  if (in_under)
    {
      printf ("%s", stop);
    }
}
