/***********************************************************************\
 *                                                                       *
 *   RELATE4.C     Copyright (C) 1993 Sequiter Software Inc.             *
 *                                                                       *
 \***********************************************************************/
/* See User's Manual, page 148 */

#include "d4all.h"

#ifdef __TURBOC__
extern unsigned _stklen = 10000;
#endif

CODE4   code_base;
DATA4   *student = NULL,*enrolment = NULL;
FIELD4  *id,*f_name,*l_name,*age,*c_code;
RELATE4 *master = NULL,*slave = NULL;
TAG4    *id_tag,*name_tag;

void open_data_files() ;
void set_relation() ;
void print_record() ;

void open_data_files()
{
  d4init(&code_base);

  student = d4open(&code_base,"STUDENT");
  enrolment = d4open(&code_base,"ENROLL");

  id = d4field(student,"ID");
  f_name = d4field(student,"F_NAME");
  l_name = d4field(student,"L_NAME");
  age = d4field(student,"AGE");
  c_code = d4field(enrolment,"C_CODE_TAG");

  name_tag = d4tag(student,"NAME");
  id_tag = d4tag(enrolment,"STU_ID_TAG");

  e4exit_test(&code_base);
}

void set_relation()
{

  master = relate4init(student);    
  slave = relate4create_slave(master, enrolment, "ID", id_tag);
}


void seek(DATA4 *data_file, TAG4 *tag, RELATE4 *relation, char *key)
{
  TAG4 *old_tag;

  old_tag = d4tag_selected(data_file);
  d4tag_select(data_file,tag);

  d4seek(data_file,key);
  relate4do(relation);

  d4tag_select(data_file,old_tag);
}


void print_record()
{
  printf("%15s ",f4str(f_name));
  printf("%15s ",f4str(l_name));
  printf("%6s ",f4str(id));
  printf("%2s ",f4str(age));
  printf("%7s\n",f4str(c_code));
}


void main()
{
  open_data_files();

  set_relation();

  seek(student
       ,name_tag
       ,master
       ,"Tyler           Harvey         ");

  print_record();

  seek(student
       ,name_tag
       ,master,"Miller          Albert        ");
  
  print_record();

  relate4unlock(master);
  relate4free(master,0);

  d4close_all(&code_base);
  d4init_undo(&code_base);
  mem4reset() ;
}
