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

#include "d4all.h"

#ifdef __TURBOC__
extern unsigned _stklen = 10000;
#endif

CODE4   code_base;
DATA4   *student,*enrollment,*classes;
FIELD4  *student_id,*first_name,*last_name,*age,*class_code,*class_title;
TAG4    *code_tag,*id_tag;
RELATE4 *class_rel,*student_rel,*enroll_rel;

void print_students() ;
void open_data_files() ;

void open_data_files()
{

  d4init(&code_base);

  student = d4open(&code_base,"STUDENT");
  enrollment = d4open(&code_base,"ENROLL");
  classes = d4open(&code_base,"CLASSES");

  student_id = d4field(student,"ID");
  first_name = d4field(student,"F_NAME");
  last_name  = d4field(student,"L_NAME");
  age = d4field(student,"AGE");
  class_code = d4field(classes,"CODE");
  class_title = d4field(classes,"TITLE");

  id_tag = d4tag(student,"ID_TAG");
  code_tag = d4tag(enrollment,"C_CODE_TAG");

  e4exit_test(&code_base);

}

void print_students()
{
  printf("\n        %s ",f4str(first_name));
  printf("%s ",f4str(last_name));
  printf("%s ",f4str(student_id));
  printf("%s ",f4str(age));
}

void set_relation()
{
  class_rel = relate4init(classes);

  enroll_rel = relate4create_slave(class_rel,enrollment,"CODE",code_tag);

  student_rel = relate4create_slave(enroll_rel,student,"STU_ID_TAG",id_tag);
}

void print_student_list(char *expr,long direction)
{
  int     rc,end_value;


  relate4query_set(class_rel,expr);
  relate4sort_set(class_rel,"STUDENT->L_NAME + STUDENT->F_NAME");

  relate4type(enroll_rel,relate4scan);

  if(direction > 0)
  {
    rc = relate4top(class_rel);
    end_value = r4eof;
  }
  else
  {
    rc = relate4bottom(class_rel);
    end_value = r4bof;
  }

  printf("\n%s",f4str(class_code));
  printf("  %s\n",f4str(class_title));

  for (;rc != end_value; rc = relate4skip(class_rel,direction))
    print_students();
}

void main()
{

  open_data_files();

  set_relation();

  print_student_list("CODE = 'MATH114 '",1L);

  print_student_list("CODE = 'CMPT411 '",-1L);

  relate4unlock(class_rel);
  relate4free(class_rel,0);

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