/* Title: readcaps.c
 * Author: Jed Marti
 * Description: Read capacitor values into a database. Each line is an integer capacitor value
 *   in picoFaraads.
 * Revision History: (Created Sat Sep 10 07:28:34 2022)
 *   Wed Sep 14 09:10:30 2022 - Allow comments and blank lines.
 */

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "caps.h"


// This is the table of capacitive values we've read in. 
double *capValues;

uint8_t readCapacitorFile(char *fname)
/*     Read a file of capacitive values. We can support up to 64 but we're limited as to the size
 *   of the permutation file (currently 64 bits). The file contains single integer values on each
 *   line which is the measured capacitance value in picoFarads. Anything following this value is
 *   ignored (a comment).
 *     We first read the file and count the number of lines and then allocate vector space for
 *   the capacitance in farads.
 * Parameters:
 *   fname: File to read.
 * External Values:
 *   capValues: Created vector for junk box capacitors. Values are stored in farads, but the input
 *     file is in integer picofarads.
 * Returned Values: The number of values read.
 * Errors detected: couldn't open file, not enough capacitors, too many capacitors, out of
 *   storage - (how big is your machine anyway?)
 */
{
  FILE    *fh;
  char    ibuf[256];
  int32_t ccnt;
  int32_t i;

  // Open file for input, exit if not found.
  if ((fh = fopen(fname, "rb")) == NULL)
  {
    fprintf(stderr, "Couldn't open capacitors file '%s'\n", fname);
    exit(-1);
  }

  // Count the number of lines is the number of capacitors. Blank line and those with # are
  // ignored.
  for (ccnt = 0;;)
  {
    if (fgets(ibuf, 256, fh) == NULL) break;
    if (ibuf[0] != 0 && ibuf[0] != '#') ++ccnt;
  }

  // Not enough (must be at least 4).
  if (ccnt < MAXCAPS)
  {
    fprintf(stderr, "%d capacitors is not enough for the %d solutions\n", ccnt, MAXCAPS);
    fclose(fh);
    exit(-1);
  }

  // Can't supprt more 64 at the current time.
  if (ccnt > 64)
  {
    fprintf(stderr, "%d capacitors is too many for this program\n", ccnt);
    fclose(fh);
    exit(-1);
  }

  // Restart and allocate storage.
  rewind(fh);
  if ((capValues = (double *) malloc(ccnt * sizeof(double))) == NULL)
  {
    fprintf(stderr, "Not enough space for %d capacitors\n", ccnt);
    fclose(fh);
    exit(-1);
  }

  // Read the values, convert to farads.
  for (i = 0;;)
  {
    if (fgets(ibuf, 256, fh) == NULL) break;
    if (ibuf[0] != 0  && ibuf[0] != '#') capValues[i++] = atof(ibuf) / 1.0E9;
  }

  // Close and exit.
  fclose(fh);
  printf("Read %d values from %s\n", ccnt, fname);
  return (uint8_t) ccnt;
}



// EOF
