/***************************************
 *************   files.c   *************
 ***************************************/

#include <exec/types.h>
#include <exec/libraries.h>
#include <intuition/intuition.h>
#include <graphics/text.h>

#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/intuition_protos.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "consts.h"
#include "structs.h"
#include "prototype.h"

extern struct Window *editWnd;

extern prjptr prj;

void readnotefile()
   {
   struct ndnode *ndptr;
   nteptr newnote;
   
   FILE *ntefp;

   char error_msg[STRLEN_ERRORMSG];
   char strpos[STRLEN_INLINE];
   char strtitle[STRLEN_INLINE];
   char strnote[STRLEN_INLINE];

   int l;

   ntefp = fopen(prj->notefile,"r");

   if (!ntefp)
      {
      sprintf(error_msg,"Could not open notefile \"%s\"",
         prj->notefile);
      error(error_msg,ERR_FOPEN);
      }

   /***   Give sleep pointer if edit window open   ***/

   if (editWnd)
      andyssleeppointer(editWnd);

   prj->no_notes = 0;

   while ((fgets(strpos,STRLEN_INLINE,ntefp)) &&
         (fgets(strtitle,STRLEN_INLINE,ntefp)) &&
         (fgets(strnote,STRLEN_INLINE,ntefp)))
      {
      /***   Strip \n from strings   ***/

      for (l = 0; l < STRLEN_INLINE; l++)
         {
         strtitle[l] = (strtitle[l] == '\n')?'\0':strtitle[l];
         strnote[l] = (strnote[l] == '\n')?'\0':strnote[l];
         }

      /*** Create a new note in the linked list   ***/

      ndptr = llealloc();
      newnote = notealloc();
      ndptr->data = newnote;

      if (!newnote)
         {
         fclose(ntefp);
         error("Can't allocate new note",ERR_MALLOC);
         }

      if ((sscanf(strpos,"%d,%d",&newnote->xpos,&newnote->ypos) != 2))
         {
         error("Error in notefile date",ERR_NOTEFILE);
         continue;
         }

      strncpy(newnote->title,strtitle,STRLEN_TITLE);
      strncpy(newnote->note,strnote,STRLEN_NOTE);

      newnote->show = TRUE;

      lleadd(prj->notes_end->prev,ndptr);

      prj->no_notes++;

      /***   Make last note current   ***/

      prj->currnode = ndptr;
      }

   fclose(ntefp);

   prj->filechanged = FALSE;

   if (editWnd)
      ClearPointer(editWnd);
   }

void writenotefile()
   {
   struct ndnode *ndptr;
   nteptr currnote;

   FILE *outfp;

   outfp = fopen(prj->notefile,"w");
       
   if (!outfp)
      {
      error("Could not save to note file",ERR_FILESAVE);
      return;
      }

   andyssleeppointer(editWnd);

   ndptr = prj->notes_start->next;

   while (ndptr->next)
      {
      currnote = ndptr->data;

      fprintf(outfp,"%d,%d\n",currnote->xpos,currnote->ypos);
      fprintf(outfp,"%s\n%s\n",currnote->title,currnote->note);

      ndptr = ndptr->next;
      }

   fclose(outfp);

   prj->filechanged = FALSE;

   ClearPointer(editWnd);
   }
