/* REFER-BibIX_IMPORT.rexx  version 1.1  */
/* This macro can be run from the CLI, SHELL or WorkBench and  */
/* acts on a text or word processor-based citation database from  */
/* which you wish to import citations in REFER-BibIX format.  The  */
/* macro generates a text file of Citation_Base compatible  */
/* citations.  */

/* open the REFER-BibIX file (database) for import */
/* NOTE: change the disk/drive designations below to suit your setup */
in_text = getfile(,,'ram:',,'Select REFER-BibIX import file');
if (in_text = '') then exit;
if (open(importfile,in_text,'R') ~= 1) then;
  do;
    say 'I could not open the file ' || in_text || ' for importing.';
    exit;
  end;

/* open the Citation_Base text file for export */
out_text = getfile(,,'ram:',,'Select citation export name');
if (out_text = '') then exit;
if (open(exportfile,out_text,'W') ~= 1) then;
  do;
    say 'I could not open the file ' || out_text || ' for exporting.';
    exit;
  end;


/* Start input-output loop for citations */
do while (~EOF(importfile));


/* Read REFER/BibIX citation */
  j = 1;
  a_num = 0;
  output = 'OK';
  do forever;
    refer.j = readln(importfile);
    if left(refer.j,2) = '%A' then a_num = a_num + 1;
    if left(refer.j,2) = '%D' then year = substr(refer.j,4);
    if left(refer.j,2) = '%T' then title = substr(refer.j,4);
    if left(refer.j,2) = '%J' then full_journal = substr(refer.j,4);
    if left(refer.j,2) = '%V' then volume = substr(refer.j,4);
    if left(refer.j,2) = '%P' then pages = substr(refer.j,4);
    if left(refer.j,2) = '%K' then keywords = substr(refer.j,4);
    if refer.j = '' then leave;
    j = j + 1;
  end;
  if j <= 1 then output = 'BAD';


/* Reconstruct author string from REFER-BibIX input */
  CB_authors = '';
  do i = 1 to a_num;
    parse var refer.i junk '%A ' initials '. ' surname;
    initials = compress(initials,' .');
    CB_authors = (CB_authors || surname || ', ' || initials || ', ');
  end;
  CB_authors = strip(CB_authors,'T',', ');


/* Extract page numbers from REFER-BibIX pages input */
  parse var pages first_page '-' last_page;
  first_page = compress(first_page);
  last_page = compress(last_page);


/* Assign abbreviate journal name the full journal name */
  journal = full_journal;


/* Append asterix to full journal name */
  full_journal = ('*' || full_journal);


/* Assign string values to the citation fields and add record */
  CB_field.1 = CB_authors;
  CB_field.2 = year;
  CB_field.3 = title;
  CB_field.4 = (journal || ', ' || volume || ', ' || first_page || ', ' || last_page || ', ' || keywords);
  CB_field.5 = full_journal;


/* Export the citation in the Citation_Base format */
  if output = 'OK' then;
    do;
      do k = 1 to 5;
        foo = writeln(exportfile,CB_field.k)
        say CB_field.k;
      end;
    end
  else NOP;


/* Get next REFER-BibIX citation or exit */
end;


/* exit macro */
say 'Imported REFER/BibIX style citations in file ' || out_text;
exit;
