/*  (c) Marietta Systems, Inc.  1987
*    All rights reserved
*
*    Test program for filewrit function
*
*    Note: This uses the file created by the test program 'filetest'
*/
#include "mtest.h"
int acptlong(long*, enum _JUST, enum ATTRIB, int);
/*  
*
*	Function to accept a long int
*
*/
int acptlong(kk, just, atb, digits)
long *kk;
enum _JUST just;
enum ATTRIB atb;
int digits;{
    int z;
    char text[15];
#ifdef LATTICE
    stcl_d(text, *kk);
#else
    ltoa(*kk, text, 10);
#endif
    z = accept(text, just, atb, digits, 0);
    *kk = atol(text);
    return z;
    }
/*  
*
*	Main program
*
*/
void main(){
long rec_nbr;
int fh1, fh2, z, x, k;
clr_scrn("Filewrit access test");
KEYMATCH[4] = 0X8000; disp_err("",1); /* activate F8 - AMEND key */
/*
*    open ascii file, and copy it into a relative file with binary
*    length records, stripping the '\n' symbol.
*/
fh1 = fileopen("testfile.dat", ascii, readonly);
fh2 = fileopen("testfile.rel", binary, recreate);
if (fh1 <= 0 || fh2 <= 0) goodbye (106);
if (fileinit(fh2, 0, 64, 0L)) goodbye(110);
display ("File opened - records ready to be read", 1, 1, low);   
rec_nbr = 1L;
for (z = 0 , x = 2 ; ; z++, x++){
     if (!(k = fileread(fh1, nextrec, &rec_nbr))) break; /* EOF */
     if (k < 0) goodbye(107); /* read error */
     FN[fh1].record[strlen(FN[fh1].record) - 1] = 0; /* delete '\n' */
     justify (left, FN[fh2].record, FN[fh1].record, 35, 0);
     rec_nbr -= 1L;
     if (filewrit(fh2, &rec_nbr) < 0) goodbye(108);
     display(FN[fh2].record, x, 1, reverse);
     }
if (fileclos(fh1) < 1 || fileclos(fh2) < 1) goodbye(109);
while (!disp_qry(" Ready to random read/write"));
/*
*    reopen file 2
*/
fh2 = fileopen("testfile.rel", binary, update);
if (fileinit(fh2, 0, 64, 20L)) goodbye(110);
if (fh2 <= 0) goodbye (106);
display ("File opened - records ready to be read", 1, 40, low); 
display ("Next record number to be actioned", 22, 44, high);
rec_nbr = 1L; 
for (;;){
	if (INCHAR == AMEND) k = fileread(fh2, nextrec, &rec_nbr);
		else k = fileread(fh2, relative, &rec_nbr);
	if (k < 0) goodbye(107); if (!k) break;
	display(FN[fh2].record, 3, 40, reverse);
	set_crsr(22,40);
	rec_nbr -= 1L; 
	z = acptlong(&rec_nbr, code, alt_reverse, 3);
 	if (!z) continue;
	if (INCHAR != AMEND) break;
	set_crsr(5, 40);
	if (accept(FN[fh2].record, left, alt_reverse, 35, 0)) 
		if (INCHAR == QUIT) break; else continue;
	filewrit(fh2, &rec_nbr);    
	}
if (fileclos(fh2) < 1) goodbye(109);
disp_msg(" Press any key to end", 1); 
read_kb();
goodbye(0);
}