/* For free support for VSIDE, please visit www.vsdsp-forum.com */

#include <vo_stdio.h>
#include <volink.h>     // Linker directives like DLLENTRY
#include <apploader.h>  // RunLibraryFunction etc
#include <consolestate.h>
#include <string.h>
#include <consolestate.h>
#include <kernel.h>


int hasPrintedAnything=0;

void Print(register char *p, register int verbose) {
  if (hasPrintedAnything) {
    printf(" ");
  }
  hasPrintedAnything = 1;
  printf("%s", p);
  if (verbose) {
    char *s = "";
    printf("(");
    while (*p) {
      printf("%s%c:%x", s, *p, *p);
      s = " ";
      p++;
    }
    printf(")");
  }
}


ioresult main(char *parameters) {
  int noMoreParams=0, nParam=0, printNewLine=1;
  int wait=0, verbose=0;
  char *p = parameters;
  int i;

  nParam = RunProgram("ParamSpl", parameters);

  for (i=0; i<nParam; i++) {
    if (!noMoreParams) {
      if (!strcmp(p, "-n")) {
	printNewLine = 0;
      } else if (!strcmp(p, "+n")) {
	printNewLine = 1;
      } else if (!strcmp(p, "-e")) {
	appFlags &= ~APP_FLAG_ECHO;
      } else if (!strcmp(p, "+e")) {
	appFlags |= APP_FLAG_ECHO;
      } else if (!strcmp(p, "-r")) {
	appFlags &= ~APP_FLAG_RAWTTY;
      } else if (!strcmp(p, "+r")) {
	appFlags |= APP_FLAG_RAWTTY;
      } else if (!strcmp(p, "-u")) {
	appFlags &= ~APP_FLAG_UTF8_CLEAN;
      } else if (!strcmp(p, "+u")) {
	appFlags |= APP_FLAG_UTF8_CLEAN;
      } else if (!strcmp(p, "-w")) {
	wait = TICKS_PER_SEC/100;
      } else if (!strcmp(p, "+w")) {
	wait = 0;
      } else if (!strcmp(p, "-v")) {
	verbose = 1;
      } else if (!strcmp(p, "+v")) {
	verbose = 0;
      } else if (!strcmp(p, "-h")) {
	printf("Usage: echo [-n|+n|-e|+e|-r|+r|-w|+w|-u|+u|-v|+v|-|-h] string\n"
	       "-n\tNo newline\n"
	       "+n\tOutput newline\n"
	       "-e|+e\tTurn shell interactive echo mode off/on\n"
	       "-r|+r\tTurn RAW tty mode off/on\n"
	       "\tWhen on, three Ctrl-C's will not reset board\n"
	       "-u|+u\tTurn UTF-8 clean mode off/on\n"
	       "\tWhen on, UTF-8 codes 0xF000-0xFFFF will work\n"
	       "-w|+w\tWait/Don't wait 10 ms after printing before exit\n"
	       "-v|+v\tVerbose on/off\n"
	       "-\tEnd of parameters\n"
	       "-h\tShow this help\n"
	       "Note: String may contain escape codes such as \\\" and \\n"
	       );
	verbose = 1;
      } else if (!strcmp(p, "-")) {
	noMoreParams = 1;
      } else {
	Print(p, verbose);
      }
    } else {
      Print(p, verbose);
    }
    p += strlen(p)+1;
  }
  if (printNewLine) {
    printf("\n");
  }

  if (verbose) {
    printf("Shell interactive echo mode %s\n"
	   "RAW tty mode %s\n"
	   "UTF-8 clean mode %s\n",
	   (appFlags & APP_FLAG_ECHO) ? "on" : "off",
	   (appFlags & APP_FLAG_RAWTTY) ? "on" : "off",
	   (appFlags & APP_FLAG_UTF8_CLEAN) ? "on" : "off");
  }
  Delay(wait);
  
  return S_OK;
}
