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

EXEC SQL typedef long mmInteger;
EXEC SQL typedef char mmChar;
EXEC SQL typedef short mmSmallInt;

EXEC SQL BEGIN DECLARE SECTION;
struct TBempl
{
  mmInteger idnum;
  mmChar name[21];
  mmSmallInt accs;
  mmChar byte[20];
};
EXEC SQL END DECLARE SECTION;

int
main (void)
{
  EXEC SQL BEGIN DECLARE SECTION;
  struct TBempl empl;
  char *data = "\\001\\155\\000\\212";
  union 
  {
	mmSmallInt accs;
	char t[2];
  } a;
  EXEC SQL END DECLARE SECTION;
  FILE *dbgs;
  int i;

  if ((dbgs = fopen ("log", "w")) != NULL)
    ECPGdebug (1, dbgs);

  empl.idnum = 1;
  EXEC SQL connect to mm;
  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 select name, accs, byte
  	into :empl.name, :empl.accs, :empl.byte
	from empl
	where idnum =:empl.idnum;
  if (sqlca.sqlcode)
    {
      printf ("select error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }
  printf ("name=%s, accs=%d byte=%s\n", empl.name, empl.accs, empl.byte);

  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);
  memset(empl.byte, '#', 20L);
  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,:a.accs,:empl.byte;
  if (sqlca.sqlcode)
    {
      printf ("fetch error = %ld\n", sqlca.sqlcode);
      exit (sqlca.sqlcode);
    }

  EXEC SQL CLOSE B;

  i=a.t[0];
  a.t[0]=a.t[1];
  a.t[1]=i;
  
  printf ("name=%s, accs=%d byte=", empl.name, a.accs);
  for (i=0; i<20; i++)
  {
  	if (empl.byte[i] == '#')
		break;
  	printf("(%o)", (unsigned char)empl.byte[i]);
  }
  printf("\n");
  EXEC SQL disconnect;
  fclose (dbgs);
  exit (0);
}
