#include <sys/ioctl.h>
#include <stdlib.h>
#include <limits.h>
#include "term.h"

int term_size_get(void)
{
    struct winsize win;
    int cols;
    char *col_str;
    int err;

    err = ioctl(1, TIOCGWINSZ, (char *)&win);
    if (err != -1 && win.ws_col > 0)
	return win.ws_col;
 
    col_str = getenv("COLUMNS");
    if (!col_str || (cols = atoi(col_str)) <= 0 || cols == INT_MAX)
	cols = 80;

    return cols;
}
