#include <stdio.h>
#include <stdlib.h>

/*
 * prototypes
 */

void ShowUsage(void);

/*
 * command structure
 */

struct TAG_SCRT_Commands
{
  char *szCommand;
  char *szDesc;
  void (*fCommand)(int, char **);
};

typedef struct TAG_SCRT_Commands SCRT_Commands;

/*
 * screen size variables
 */

int iLines;
int iColumns;

/*
 * colour codes
 */

char *szColor_Default		= "[0m";
char *szColor_Bold		= "[1m";
char *szColor_Blink		= "[5m";
char *szColor_Hide		= "[8m";

char *szColor_Fore_Black	= "[30m";
char *szColor_Fore_Red		= "[31m";
char *szColor_Fore_Green	= "[32m";
char *szColor_Fore_Yellow	= "[33m";
char *szColor_Fore_Blue		= "[34m";
char *szColor_Fore_Magenta	= "[35m";
char *szColor_Fore_Cyan		= "[36m";
char *szColor_Fore_White	= "[37m";

char *szColor_Back_Blue		= "[44m";

/*
 * other ANSI sequences
 */

char *szErase			= "[2J";

/*
 * other global variables
 */

char *szProgram;
  /* the name of the process */

/*
 * support routines - not callable from the command line
 */

void fGoHome (void)
{
  printf("[1; 1H");
}

/*
 * routines which can be called from the command line
 */

void fErase (int argc, char *argv[])
{
  if (argc > 0)
    ShowUsage();
  printf("%s%s%s", szColor_Back_Blue, szColor_Fore_Cyan, szErase);
  fGoHome();
}

void fTitle (int argc, char *argv[])
{
  int iLen;
  int iIndex;
  
  if (argc > 1)
    ShowUsage();
  
  fErase(0, NULL);
    /* erase the screen */
  
  printf(" %s\n ", argv[0]);
  iLen = iColumns - 1;
  for (iIndex = 2; iIndex < iLen; iIndex++)
    printf("-");
}

SCRT_Commands stCommands[] =
{
  { "--erase",	"clear the screen",					fErase	},
  { "--title",	"clear the screen and put a new title at the top",	fTitle	},
  { NULL,	NULL,							NULL	}
};

void ShowUsage(void)
{
  SCRT_Commands *pstWalker;
  
  printf("Usage: %s command [ parameters ]\r\n\r\n", szProgram);
  
  for (pstWalker = &stCommands[0]; pstWalker->szCommand != NULL; pstWalker++)
    printf("  %s\t%s\r\n", pstWalker->szCommand, pstWalker->szDesc);
  printf("\r\n");
  exit(1);
}
  
int main(int argc, char *argv[])
{
  char *szTmp;
  SCRT_Commands *pstWalker;
  
  szProgram = argv[0];
  if ((szTmp = getenv("LINES")) == NULL)
    iLines = 25;
  else
    iLines = atoi(szTmp);
  
  if ((szTmp = getenv("COLUMNS")) == NULL)
    iColumns = 80;
  else
    iColumns = atoi(szTmp);

  if (argc < 2)
    ShowUsage();
  
  for (pstWalker = &stCommands[0]; pstWalker->szCommand != NULL; pstWalker++)
  {
    if (!strncmp(pstWalker->szCommand, argv[1], strlen(pstWalker->szCommand)))
    {
      pstWalker->fCommand(argc-2, argv+2);
      exit(0);
    }
  }
  
  /*
   * at this point, we have not found a command which we support
   */
  
  ShowUsage();
}
