/* UNIX like pager for Mint/TOS on ATARI ST.  Kees Lemmens; Juli 1992

   Also works on virtual screens (windows) and with pipes as in 
   "ls -la | more"
   If 'q' is pressed the pager aborts, any other key continues.
   A / (slash) can be used to enter a string to search for.
   
   Uses environment variables LINES and COLUMNS (SYSV), or a default
   of 25x80 if these are not found.

   Any questions or suggestions about this program can be send to:
   lemmens@dv.twi.tudelft.nl
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "ux_misc.h"

#define DEFCOLS   80
#define DEFLINS   25
#define MAXLEN	1000

void clearline(void)
{	fprintf(stdout,"\r               \r");
}

void getstring(char *str)
{	while(read(1,str,1), *str != '\r') str++;
	*str='\0';
}

char putmore(void)
{	char ch;

	fprintf(stdout,"  More ...");
	read(1,&ch,1);
	clearline();
	return ch;
}

void pagefile(FILE *in, int nrln, int nrcl)
{	int cn=1;
    size_t stl;
	char *tmp,buffer[MAXLEN],str[100];

	while(!feof(in))
	{	for(;cn<nrln && !feof(in);cn++)
		{	*buffer='\0';
			fgets(buffer,MAXLEN-1,in);
			if((stl=strlen(buffer)) > nrcl)
				strcat(buffer+nrcl-1,"\n\0");
			if(strrchr(buffer,'\n') == NULL)
				strcat(buffer+stl,"\n\0");
			fprintf(stdout,buffer);
		}
		cn=1;
		if (!feof(in))
		{	switch(toupper(putmore()))
			{	case 'Q':	putchar('\n');
							exit(0);
							break;
				case '/':	putchar('/');
							getstring(str); /* don't read pipe */
							do
							{	fgets(buffer,MAXLEN,in);
								tmp=strstr(buffer,str);
							}while(tmp==NULL && !feof(in));
							if(tmp != NULL)
							{	clearline();
								fprintf(stdout,buffer);
								cn++;
							}
							else	return;
							break;
			}
		}
	}
}

void main(int argc,char *argv[]) 
{   FILE *in;
	char *tmp;
    int nrln,nrcl,multiflag = 0;
	char *streep= "\n----------\n";
	
	tmp  = getenv("LINES");
	nrln = (tmp == NULL) ? DEFLINS : atoi(tmp);
	tmp  = getenv("COLUMNS");
	nrcl = (tmp == NULL) ? DEFCOLS : atoi(tmp);

	if (argc == 1)
	{	pagefile(stdin,nrln,nrcl);
		exit(0);
	}
	if(argc > 2)
		multiflag = 1;	/* more than one file */

	while(argc-- > 1)
	{	if(multiflag)
		{	fprintf(stdout,"%s%s%s",streep,argv[argc],streep);
			putmore();
		}
		ux2dos(argv[argc]);	/* convert slashes */
		if ((in = fopen(argv[argc],"r")) == NULL)
		{	fprintf(stderr,"\nCan't open <%s>\n",argv[argc]);
			continue; 
		}
		pagefile(in,nrln,nrcl);
		fclose(in);
	}
	exit(0);
}
