#include "config.h"
#include <stdio.h>
#include <sys/types.h>
#include <setjmp.h>
#include "common.h"
#ifdef X68
#include "tty_x68.h"
#else
#ifdef WIN32
#include "tty_w32.h"
#else
#include "tty.h"
#include <termios.h>
#endif
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#include "command.h"

#if 0
# define dprintf(x)	fprintf x
#else
# define dprintf(x)
#endif

extern int verbose;


/*------------------------------------------------------------*/

int
QVdeletepicture(n)
     int	n;
{
  u_char	s;

  if (!QVok())
    return -1;			/*ng*/
  wstr("DF", 2);
  wbyte((u_char) n);
  wbyte(0xff);
  s = rbyte();			/*supposed to be 0x76 - n*/
  wbyte(ACK);
  return 1;
}

int
QVtakepicture()
{
  u_char	s;

  if (!QVok())
    return -1;			/*ng*/
  wstr("DR", 2);
  s = rbyte();			/*?*/
  wbyte(ACK);
  s = rbyte();			/*?*/
  return 1;
}

int
QVmovepicture(from, to)
     int from;
     int to;
{
  u_char	s;

  if (!QVok())
    return -1;			/*ng*/
  wstr("DI", 2);
  wbyte((u_char) from);
  s = rbyte();			/*  0x72 - from ?*/
  wbyte(ACK);

  if (!QVok())
    return -1;			/*ng*/
  wstr("DY", 2);
  wbyte(0x02);
  wbyte((u_char) from);
  s = rbyte();			/* ?*/
  wbyte(ACK);

  if (!QVok())
    return -1;			/*ng*/
  wstr("DF", 2);
  wbyte((u_char) from);
  wbyte(0xff);
  s = rbyte();			/*  0x76 - from ?*/
  wbyte(ACK);

  if (!QVok())
    return -1;			/*ng*/
  wstr("Dj", 2);
  wbyte((u_char) to);
  s = rbyte();			/* 0x51 - to ? */
  wbyte(ACK);

  return 1;
}

int
QVgetpicture(n, buf, format)
     int	n;
     u_char	*buf;
     int format;
{
  u_char	s;
  int	len;

  if (QVshowpicture(n) < 0)
    return -1;			/*ng*/

  /* drain */
  if (!QVok())
    return -1;			/*ng*/

  switch(format){
  case PPM_T:
  case RGB_T:
  case BMP_T:
    wstr("DH", 2);
    wbyte((u_char) n);
    s = rbyte();		/*supposed to be 0x73 - n*/
    wbyte(ACK);
    wstr("MK", 2);
    break;
  case PPM_P:
  case RGB_P:
  case BMP_P:
    wstr("ML", 2);
    break;
  case JPEG:
  default:
    wstr("MG", 2);
    break;
  }
  s = rbyte();			/*?*/
  wbyte(ACK);
  if (verbose){
    switch(format){
    case PPM_T:
    case RGB_T:
    case BMP_T:
      fprintf(stderr, "Thumbnail %3d: ", n);
      break;
    case PPM_P:
    case RGB_P:
    case BMP_P:
    case JPEG:
    case CAM:
    default:
      fprintf(stderr, "Picture   %3d: ", n);
      break;
    }
  }
  len = QVblockrecv(buf);

  if (!QVok())
    return -1;			/*ng*/

  return len;
}

