/* liste.c
   Functions for a list of numbers */


#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "liste.h"

t_data liste[NMAX];
int n;                /* number of elements in the list */

void init(void)
{
  n = 0;
}

int insert (t_data d)
{
  int i, j;

  if (n == NMAX) {
    return 0;
  }

  /* Searching for the right position for the new element.
     The list always must be ascendingly sorted. */

  i = 0;
  while (i < n && d > liste[i])
    i++;

  if (i == n)  /* we can add the new element at the end */
  {
    liste[n] = d;
    n++;
  }
  else
  {
    /* insert the element, to do this
       1) we move all elements with a position j >= i
          from position j to position j+1
       2) we insert the element into the gap
    */
    for (j = n; j > i; j--)
      liste[j] = liste[j-1];
    liste[i] = d;
    n++;
  }
  return 1;
}


int delete (t_data d)
{
  int i, j;

  if (n == NMAX) {
    return 0;
  }

  /* Search the element, simplest method */

  i = 0;
  while (i < n && d != liste[i])
    i++;

  if (i == n)
  {
    printf("Value not found\n");
    return 0;
  }
  else
  /* Remove the element.
     To do this, we must move all elements above the element to be removed.
       5
       3   5
     <-2   3
       1   1
      This works like removing a element from a pile.
  */
  {
    for (j = i+1; j < n; j++)
      liste[j-1] = liste[j];
    n--;
  }
  return 1;
}


void show()
{
  int i;
  for (i = 0; i < n; i++)
    printf("%3i: "FORMAT"\n", i+1, liste[i]);
}

void writefile(void)
{
  char filename[80];
  FILE *fout;

  printf("Write to file : ");
  scanf("%s", filename);

  fout = fopen(filename, "w");
  int i;
  for (i = 0; i < n; i++)
    fprintf(fout, FORMAT"\n", liste[i]);
  fclose(fout);
}

void readfile(void)
{
  char filename[80];
  FILE *fin;
  int i;

  printf("Read from file : ");
  scanf("%s", filename);

  if ((fin = fopen(filename, "r")) == NULL) {
    printf("File not found\n");
    return;
  }

  i = 0;
  while (fscanf(fin, FORMAT, &liste[i]) != EOF)
     i++;

  n = i;
  fclose(fin);
  show();
}