/* Database system C example:
   fsd_excld, fsd_incld, fsd_srch, and fsd_srchc,
   using a user written compare routine to check the records.
*/
#include <stdlib.h>
#include <qdos.h>
#include <stdio.h>
#include <string.h>
#include <database.h>

FILE *stream;
long chid,dbid;
int compare();
void rec_dump();

main(argc,argv)
int argc;
char *argv[];
{
   if (argc<2)
   {
      printf("Format: ex flp2_DBC_bin;'database_name'\n");
      exit(-1);
   }

   printf("%s\n",argv[1]);
   stream = fopen(argv[1],"rb+");
   if(stream == 0) exit(_oserr);

   chid = fgetchid(stream);
   if (chid == -1) exit(_oserr);

   dbid = fsd_open(chid);
   if (dbid < 0) exit(_oserr);
   printf("At address: $%lx\n",dbid);
   printf("Press ENTER to continue\n");
   getchar();

   if (dbid < 0) exit(_oserr);

   if (fsd_excld(dbid,compare,"EUROPE") == -1) exit(_oserr);
   rec_dump(dbid);
}

/* Dump out the number of records followed by the first field
   in every record */
void rec_dump(db)
int db;
{
   char store[32];
   int count,loop,length;
   printf("%d records\n",count = fsd_rcnt(db) );

   if(count == 0) exit(0);
   for(loop=0; loop<count; loop++) {
      fsd_posa(db,loop);
      length = fsd_get(db,1,31,store);
      store[length]=0;
      printf("'%s'\n",store);
   }
}

/* Check the record example routine */
int compare(dbid,rec,fldef,appcn)
long dbid;                          /* database ID */
char *rec;                          /* pointer to record */
struct fld_list fldef[];            /* field list */
char *appcn;                        /* application definable quantity; in
                                       this case, the compare string */
/* return: =0 don't act;  <>0 do act.
   What type of action taken depends on the calling routine, eg:
   fsd_excld will exclude a record if return <>0   */
{
   size_t stln;
   struct QLSTR *string;

   /* make a pointer to field 2 */
   string = (struct QLSTR *) (rec + fldef[2].fld_ptr);

   /* get the length of the string */
   stln = string->qs_strlen;

   /* 
      actually compare the strings - signal act if strings are unequal
      eg: exclude if continent$ != "EUROPE"
   */
   return strncmp(string->qs_str,appcn,stln);
}
