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

EXEC SQL include ../regression;

EXEC SQL BEGIN DECLARE SECTION;
struct TBempl
{
  long idnum;
  char name[21];
  short accs;
  char byte[20];
};
EXEC SQL END DECLARE SECTION;

int
main (void)
{
  EXEC SQL BEGIN DECLARE SECTION;
  struct TBempl empl;
  char *pointer = NULL;
  char *data = "\\001\\155\\000\\212";
  EXEC SQL END DECLARE SECTION;
  int i;

  ECPGdebug (1, stderr);

  empl.idnum = 1;
  EXEC SQL connect to REGRESSDB1;
  if (sqlca.sqlcode)
    {
      printf ("connect error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL create table empl
    (idnum integer, name char (20), accs smallint, byte bytea);
  if (sqlca.sqlcode)
    {
      printf ("create error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL insert into empl values (1, 'first user', 320, :data);
  if (sqlca.sqlcode)
    {
      printf ("insert error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL DECLARE C CURSOR FOR select name, accs, byte from empl where idnum =:empl.idnum;
  EXEC SQL OPEN C;
  EXEC SQL FETCH C INTO:empl.name,:empl.accs,:empl.byte;
  if (sqlca.sqlcode)
    {
      printf ("fetch error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  printf ("name=%s, accs=%d byte=%s\n", empl.name, empl.accs, empl.byte);

  memset(empl.name, 0, 21L);
  EXEC SQL DECLARE B BINARY CURSOR FOR select name, accs, byte from empl where idnum =:empl.idnum;
  EXEC SQL OPEN B;
  EXEC SQL FETCH B INTO :empl.name,:empl.accs,:empl.byte;
  if (sqlca.sqlcode)
    {
      printf ("fetch error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL CLOSE B;

  /* do not print a.accs because big/little endian will have different outputs here */
  printf ("name=%s, byte=", empl.name);
  for (i=0; i<4; i++)
	printf("(%o)", (unsigned char)empl.byte[i]);
  printf("\n");

  EXEC SQL DECLARE A BINARY CURSOR FOR select byte from empl where idnum =:empl.idnum;
  EXEC SQL OPEN A;
  EXEC SQL FETCH A INTO :pointer;
  if (sqlca.sqlcode)
    {
      printf ("fetch error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL CLOSE A;

  printf ("pointer=");
  for (i=0; i<4; i++)
	printf("(%o)", (unsigned char)pointer[i]);
  printf("\n");
  free(pointer);

  EXEC SQL disconnect;
  exit (0);
}
