/******** setup.c *********/
/* MIMD code version 3 */

#include LATDEF
#include <string.h>

/* First, scan the file and find the value */

void scan_label_value(FILE *f,char *s,char *fmt,void *val)
{
  char *p,buf[200],line[200];

  do {
    if (fgets(line,198,f) == NULL) {
      sprintf(buf," *** Error reading input element %s",s);
      halt(buf);
    }
    for (p=line; *p == ' ' || *p == '\t'; p++) ;
  } while (*p == '\n');

  if (strncmp(p,s,strlen(s)) != 0) {
    sprintf(buf," *** Input: should be '%s', does not match '%s'",s,p);
    halt(buf);
  }
  p += strlen(s);
  if (sscanf(p,fmt,val) != 1) {
    sprintf(buf," *** Unable to get the value for input %s",s);
    halt(buf);
  }
}


double get_d(FILE *f,char *s,int bcast)
{
  double val;

  if (this_node == 0) {
    scan_label_value(f,s," %lg",&val);
    if (bcast >= 0) printf("     %-30s  %g\n",s,val);
  } else val = 0;

  if (bcast) broadcast_double( &val );
  return(val);
}


int get_i(FILE *f,char *s,int bcast)
{
  int val;

  if (this_node == 0) {
    scan_label_value(f,s," %d",&val);
    if (bcast >= 0) printf("     %-30s  %d\n",s,val);
  } else val = 0;

  if (bcast) broadcast_int( &val );
  return(val);
}


int get_s(FILE *f, char *s, char *target, int bcast)
{
  int len;
  if (this_node == 0) {
    scan_label_value(f,s," %s",target);
    if (bcast >= 0) printf("     %-30s  %s\n",s,target);
  } 
  len = strlen(target);

  if (bcast) broadcast_field(target, len);
  return(len);
}

/* get one item from a list */

int get_item(FILE *f, char *s, char *items[],int n_items, int bcast)
{
  char label[200];
  int i;

  if (this_node == 0) {
    scan_label_value(f,s," %s",label);
    if (bcast >= 0) printf("     %-30s  %s\n",s,label);
    /* Find the matching string */
    for (i=0; i<n_items && strcmp(items[i],label)!=0; i++) ;
    if (i==n_items) {
      printf(" ** Input '%s' must be one of:\n ** ",s);
      for (i=0; i<n_items; i++) printf("%s, ",items[i]);
      printf("\n");
      halt("");
    }
  }
  
  if (bcast) broadcast_int( &i );
  return(i);
}

  

void print_d(FILE *f,char *s,double val)
{
  char line[130];
  if (fprintf(f,"%-30s   %g\n",s,val) <= 0) {
    sprintf(line," I/O error while printing %s",s);
    halt(line);
  }
}

void print_i(FILE *f,char *s,int val)
{
  char line[130];
  if (fprintf(f,"%-30s   %d\n",s,val) <= 0) {
    sprintf(line," I/O error while printing %s",s);
    halt(line);
  }
}

void print_s(FILE *f, char *s, char *val)
{
  char line[130];

  if (fprintf(f,"%-30s   %s\n",s,val) <= 0) {
    sprintf(line," I/O error while printing %s",s);
    halt(line);
  }
}


