#include <libraries/dos.h>
#include <libraries/dosextens.h>

long DosBase=0;                     /*Dos library base*/
struct FileHandle *inputfilehandle; /*filehandle pointer*/
struct FileLock *lock;              /*lock pointer*/
long success=0;                     /*success or failure flag*/
char *filename="limerick";          /*text filenames  used by 'files' program*/
char *filename2="limerick2";

/*prototypes*/ 
void cleanup();
int openfile(),lockfile();

main()
{
  DosBase= OpenLibrary(DOSNAME,0);      /*open the Dos library, if possible*/
  if (DosBase == 0) 
    {
       cleanup ("Unable to open the Dos Library");
       exit(1);                  /*exit if there is no library*/
    }

  success=openfile();            /*open the text file*/
  if (success !=  0)             /*clean up and exit is unsuccessful*/
    {
       cleanup("Error opening file"); 
       exit(1);
    };	
  printf("Process 1 \n");        /*run 'files' program, first text file open*/
  Execute("files",0,0);
  Close(inputfilehandle);
  printf("\n \nProcess 2 \n");   /*run 'files' program,text files closed*/ 
  Execute("files",0,0);
  success = lockfile();          /*obtain lock for second file*/
  if (success !=  0)             /*clean up and exit if unsuccessful*/
    {
       cleanup("Error locking file"); 
       exit(1);
    };	
  printf("\n \nProcess 3 \n"); /*run 'files' program,second text file locked*/
  Execute("files",0,0);
  UnLock(lock);
  printf("\n \nProcess 4 \n"); /*run 'files' program,text files unlocked*/
  Execute("files",0,0);
  cleanup("advfiles ok\n");    /*close libraries, free buffer*/
  return(0);
}

void cleanup(errormsg)         /*tidy up any loose ends*/        
{    
  printf(errormsg);            /*display error message*/
  if (DosBase !=0) CloseLibrary(DosBase); /*close library*/
  return;
}

int openfile()                  /*open file if possible*/
{
  inputfilehandle=(struct FileHandle *) Open(filename,MODE_READWRITE);
  if (inputfilehandle == NULL) 
     {
       printf("Cannot open file %s \n",filename);
       return(1);
     }
  return(0);
}

int lockfile()                /*lock file if possible*/
{ 
   lock = (struct FileLock *) Lock(filename2,EXCLUSIVE_LOCK);
   if (lock ==NULL)
      {
        printf("Cannot obtain a lock for file %s \n",filename2);
        return(1);
      }
   return(0);
} 
