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

static char device[80], command[80];
static int quit;
static float tempX, tempP, tempC;

pTecsClient TeccInit(char *startcmd, int port) {
  CocConn *conn;

  ERR_SP(conn=(CocConn *)malloc(sizeof(*conn)));
  ERR_I(CocInitClient(conn, "", port, "#rwacs", 0, startcmd));
  CocDefFlt(tempC, CocRD);
  CocDefFlt(tempP, CocRD);
  CocDefFlt(tempX, CocRD);
  CocDefStr(device, CocWR);
  CocDefInt(quit, CocWR);
  CocDefCmd(command);

  return((pTecsClient)conn);
  OnError: return(NULL);
}

int TeccSetDev(pTecsClient conn, char *dev) {
  str_copy(device, dev);
  ERR_I(CocCmd(conn, "[device]"));
  return(0);
  OnError: return(-1);
}

char *TeccGetDev(pTecsClient conn) {
  ERR_I(CocCmd(conn, "device"));
  return(device);
  OnError: return(NULL);
}

int TeccGet3(pTecsClient conn, float *tC, float *tX, float *tP) {
  ERR_I(CocCmd(conn, "tempC,tempX,tempP"));
  *tC=tempC;
  *tX=tempX;
  *tP=tempP;
  return(0);
  OnError: return(-1);
}

int TeccGet(pTecsClient conn, float *temp) {
  ERR_I(CocCmd(conn, "tempP"));
  *temp=tempP;
  return(0);
  OnError: return(-1);
}

int TeccSet(pTecsClient conn, float temp) {
  tempC=temp;
  ERR_I(CocCmd(conn, "[tempC]"));
  return(0);
  OnError: return(-1);
}

int TeccSend(pTecsClient conn, char *cmd, char *reply, int replyLen) {
  char *res;
  int cnt;

  str_copy(command, cmd);
  ERR_I(CocCmd(conn, "[$]"));
  cnt=40;
  CocDelay(100);
  while (cnt>0) {
    ERR_I(CocCmd(conn, "$"));
    if (command[0]!='\0') {
      str_ncpy(reply, command, replyLen);
      return(0);
    }
    CocDelay(250);
    cnt--;
  }
  str_ncpy(reply, "<no response>", replyLen);
  return(0);
  OnError: return(-1);
}

int TeccQuitServer(pTecsClient conn) {
  quit=1;
  ERR_I(CocCmd(conn, "[quit]"));
  return(0);
  OnError: return(-1);
}

void TeccClose(pTecsClient conn) {
  if (conn!=NULL) {
    CocCloseClient(conn);
    free(conn);
  }
}

#ifdef __VMS

int TeccSetDevVms(pTecsClient conn, char **dev) {
  int l;

  l=*(short *)dev;
  if (l>=sizeof(device)) l=sizeof(device)-1;
  strncpy(device, dev[1], l);
  while (l>0 && device[l-1]==' ') l--; /* trim */
  device[l]='\0';
  ERR_I(CocCmd(conn, "[device]"));
  return(0);
  OnError: return(-1);
}

int TeccGetDevVms(pTecsClient conn, char **dev) {
  int l, ld;

  ERR_I(CocCmd(conn, "device"));
  ld=strlen(device);
  l=*(short *)dev;
  if (ld>=l) ld=l;
  strncpy(dev[1], device, ld);
  return(ld);
  OnError: return(-1);
}

int TeccSendVms(pTecsClient conn, char **cmd, char **reply) {
  int l, lr;
  char cbuf[80], rbuf[80];

  l=*(short *)cmd;
  if (l>=sizeof(cbuf)) l=sizeof(cbuf)-1;
  strncpy(cbuf, cmd[1], l);
  while (l>0 && cbuf[l-1]==' ') l--; /* trim */
  cbuf[l]='\0';
  ERR_I(TeccSend(conn, cbuf, rbuf, sizeof(rbuf)));
  lr=strlen(rbuf);
  l=*(short *)reply;
  if (lr>=l) lr=l;
  strncpy(reply[1], rbuf, lr);
  return(lr);
  OnError: return(-1);
}
#endif
