#include <string.h>
#include "util.h"

STACKDEF(char *,charp);

const char *strclone(const char *s) {
  char *n=malloc(strlen(s)+1);
  assert(n);
  strcpy(n,s);
  return n;
}

int exactIsStr(const char *test, const char *gold) {
  /* return 1 if test is gold, 0 otherwise */
  return (strncmp(test,gold,strlen(gold))==0) && (strlen(test)==strlen(gold));
}

void chomp (char *s) {
  /* remove, in-place, final CR-LF from a string */
  int l;
  l=strlen(s);
  if (s[l-1]=='\n') {
    s[l-1]='\0';
    if (s[l-2]=='\r') {
      s [l-2]='\0';
    }
  }
}

#ifndef UNIX
#include <windows.h>
/* Windows-only */


const char *readline(const char *prompt) {
  char *ret=NULL;
  DWORD numread;

  ret=calloc(MAX_INPUT_LINE,1);
  ReadFile(GetStdHandle(STD_INPUT_HANDLE),ret,MAX_INPUT_LINE,&numread,NULL);
  chomp(ret);

  return ret;
}

void wperror() {
  /* windows version of perror, using GetLastError.  
     The actual windows perror only works with runtime library stuff,
     not with standard API errors.
     This code basically from the example call to FormatMessage in the MSDN 
     docs.  
   */
  LPVOID lpMsgBuf;
  FormatMessage( 
      FORMAT_MESSAGE_ALLOCATE_BUFFER | 
      FORMAT_MESSAGE_FROM_SYSTEM | 
      FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL,
      GetLastError(),
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
      (LPTSTR) &lpMsgBuf,
      0,
      NULL );
  fprintf(stderr,"%s",lpMsgBuf);
}

#endif

