/*
diskio.c: disk io procedures for selectnews

Copyright (C) 1993 Eugene Eric Kim
All rights reserved.

LAST REVISION: September 4, 1993
*/

#include <stdio.h>
#include <string.h>
#include "headers.h"

void error(s)
char* s;
{
  fprintf(stderr, s);
  exit(1);
}

FILE* GetFile()
{
  FILE *temp;

  if ( (temp = fopen(".newsrc", "r")) == NULL )
    error("Cannot open .newsrc: make sure you are in your home directory.\n");
  else
    return temp;
}

void Backup()
{
  FILE *from,*to;
  char line[LEN];

  if ((from = fopen(".newsrc","r")) == NULL)
    error("Cannot open .newsrc: make sure you are in your home directory");
  if ((to = fopen(".newsrc.old","w")) == NULL)
    error("Cannot write backup file.  Exiting.");
  while (fgets(line,LEN,from) != NULL)
    fputs(line,to);
  close(from);
  close(to);
}

short validstring(str)
char str[LEN];
{
  int i = 0;
  short valid = 1, found = 0; /* found = 1 if ':' or = 2 if '!' */

  while (str[i]!='\n' && valid) {
    if (!found) {
      switch (str[i]) {
      case ' ': case '\0':
	valid = 0;
	break;
      case ':':
	found = 1;
	break;
      case '!':
	found = 2;
	break;
      default:
	break;
      }
    }
    else {
      switch (str[i]) {
      case '1': case '2': case '3': case '4': case '5': case '6':
      case '7': case '8': case '9': case '0': case ' ': case '-':
      case ',':
	break;
      default:
	valid = 0;
	break;
      }
    }
    i++;
  }
  if ( (found == 1) && valid)
    return 1;
  else if ( (found == 2) && valid)
    return 0;
  else
    return -1;
}

void sortfile(f,b1,b2,i,j)
FILE *f;
dllist* b1;
dllist* b2;
int *i;
int *j;
{
  char line[LEN];
  short where;  /* 1 = sub; 0 = usub; -1 = trouble */
  node* c1;
  node* c2;

  (*i) = (*j) = 0;
  c1 = list_start(*b1);
  c2 = list_start(*b2);
  while (fgets(line,LEN,f) != NULL) {
    if (line[0] != '\n') {
      where = validstring(line);
      if (where == 1) {
	c1 = list_insafter(b1,c1,line);
	(*i)++;
      }
      else if (where == 0) {
	c2 = list_insafter(b2,c2,line);
	(*j)++;
      }
      else {
	fprintf(stderr,"Error: .newsrc file corrupt at line %d:\n   ",*i + *j + 1);
	fprintf(stderr,"%s\n",line);
	exit(1);
      }
    }
  }
  fclose(f); /* close .newsrc */
}

int Write(b1,b2)
dllist b1;
dllist b2;
{
  FILE *to;
  int i;
  node* c1;
  node* c2;

  Backup();
  if ( (to=fopen(".newsrc","w")) == NULL)
    error("Can't write .newsrc. Exiting");
  c1 = list_start(b1);
  while (c1 != 0) {
    i = 0;
    while ( (*c1).entry[i]!='\0') {
      if ( (*c1).entry[i]=='!')
	putc(':',to);
      else
	putc((*c1).entry[i],to);
      i++;
    }
    c1 = list_next(c1);
  }
  c2 = list_start(b2);
  while (c2 != 0) {
    i = 0;
    while ( (*c2).entry[i]!='\0') {
      if ( (*c2).entry[i]==':')
	putc('!',to);
      else
	putc((*c2).entry[i],to);
      i++;
    }
    c2 = list_next(c2);
  }
  fclose(to);
  return 1;
}
