Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-18 07:41:09

0001 /*
0002  * Copyright 2000-2003 Virginia Commonwealth University
0003  * -----------------------------------------------------------------------------
0004  *
0005  * Permission is hereby granted, free of charge, to any person obtaining a copy
0006  * of this software and associated documentation files (the "Software"), to deal
0007  * in the Software without restriction, including without limitation the rights
0008  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
0009  * copies of the Software, and to permit persons to whom the Software is furnished
0010  * to do so, subject to the following conditions:
0011  *
0012  * The above copyright notice and this permission notice shall be included in all
0013  * copies or substantial portions of the Software.
0014  *
0015  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0016  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0017  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
0018  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
0019  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
0020  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
0021  * THE SOFTWARE.
0022  *
0023  *-----------------------------------------------------------------------------
0024  *
0025  *   AUTHORS:
0026  *
0027  *   Jeffrey Vincent Siebers
0028  *   e-mail: jsiebers@vcu.edu
0029  *   Virginia Commonwealth University
0030  *   401 College Street, P.O.Box 980058
0031  *   Richmond, Viriginia 23298-0058
0032  *   Phone: +1-804-6287771
0033  *
0034  *
0035 */
0036 /*  General Utilities for CPP programs
0037       File Created:
0038             18-December-1995: Combined ok_check.cpp and some open_file
0039       Modification History:
0040             01-Feb-1996: JVS: filename used in open_file has extension only in openfile
0041             09-Feb-1996: JVS: Add eprintf: outputs to screen and a buffer called pbuffer
0042                                                 pbuffer is a global whose memory must be allocated
0043                                                 this is useful for creating a "history" file
0044       17-June-1996: JVS: change latex_string so will work with win95/bc5.0
0045                          cannot have for(int i=0,j=0; ). j will not increment.
0046       05-Sept-1996: JVS: Add allocate_pbuffer and print_runtime_info
0047       23-April-1997: JVS: Add interpolate
0048       06-Jan-1998: JVS: Add array_read
0049       11-June-1998: jvs: add eprintf and view_errors
0050       22-Sept-1998: JVS: fix memory leak in eprintf
0051       07-Dec-1998: JVS: Add clean_name
0052       18-Feb-1999: JVS: eliminate atof in array_read because of failures
0053       25-Feb-1999: JVS: array_read will now read numbers that start with .
0054       26-Feb-1999: JVS: Add array_read for strings
0055       02-March-1999: JVS: Add global eprint_mode so can quite eprintf statements
0056       24-March-1999: JVS: Modify clean_name so names cannot have *'s in them
0057       July 20, 1999: JVS: eprintf modified to use fprintf(stdout), rather than printf
0058       Dec 3, 1999: JVS: Add check_byte_order
0059       Jan 11, 2000: JVS: Modify clean_name so names cannot have / in them
0060       Jun 16, 2000: JVS: Change open_file so will read in .extension properly when a . is in
0061                          the path name
0062       April 25, 2001: JVS: Add cp(SourceFile,DestinationFile)
0063       May 29, 2001: JVS: clean_name now removes & as well
0064       May 31, 2002: add reverse_short_byte_order
0065       Feb 18, 2004: JVS: Add writeBigEndianBinaryFile()
0066       Feb 10, 2005: JVS: Add writeLittleEndianBinaryFile() and writeBinaryFile()
0067       Feb 11, 2005: JVS: Add reverse_int_byte_order
0068       April 21, 2005: JVS: Add readBinaryDataFromFile
0069 */
0070 #if (defined WIN32) || (defined WIN64)
0071 #include <iostream>  // so that namespace std becomes defined
0072 #endif
0073 #include <cstdio>
0074 #include <cstdlib>
0075 #include <cstring>
0076 #include <cmath>
0077 #include <cctype>
0078 #include <ctime>
0079 
0080 #if !(defined WIN32) && !(defined WIN64)
0081 using namespace std;
0082 #endif
0083 
0084 #include "utilities.h"
0085 
0086 /* ************************************************************************** */
0087 int reverse_int_byte_order(int xold)
0088 {
0089    int xnew;
0090    char *pn   = (char *) &xnew;
0091    char *po   = (char *) &xold;
0092    pn[0] = po[3];
0093    pn[1] = po[2];
0094    pn[2] = po[1];
0095    pn[3] = po[0];
0096    return(xnew);
0097 }
0098 /* *************************************************************************** */
0099 float reverse_float_byte_order(float xold)
0100 {
0101    float xnew;
0102    char *pn   = (char *) &xnew;
0103    char *po   = (char *) &xold;
0104    pn[0] = po[3];
0105    pn[1] = po[2];
0106    pn[2] = po[1];
0107    pn[3] = po[0];
0108    return(xnew);
0109 }
0110 /* **************************************************************************** */
0111 short reverse_short_byte_order(short xold)
0112 {
0113    short xnew;
0114    char *pn   = (char *) &xnew;
0115    char *po   = (char *) &xold;
0116    pn[0] = po[1];
0117    pn[1] = po[0];
0118    return(xnew);
0119 }
0120 /* **************************************************************************** */
0121 int check_byte_order()
0122 {
0123   /* Determine the byte order on this machine */
0124   float ftest=1.0f; /* assign a float to 1.0 */
0125   char *pf = (char *) &ftest;
0126   // printf("\n \t %x %x %x %x", pf[0],pf[1],pf[2],pf[3]);
0127   if(pf[0] == 0 && pf[3] != 0)
0128   {
0129     // printf("\n\n Byte order: INTEL / ALPHA,LINUX -> LITLE_ENDIAN \n");
0130     return(LITTLE_ENDIAN);
0131   }else if(pf[0] != 0 && pf[3] == 0)
0132   {
0133     // printf("\n\n Byte order: OTHER (SGI,SUN-SOLARIS) -> BIG_ENDIAN \n ");
0134     return(BIG_ENDIAN);
0135   }
0136   else
0137   {
0138         printf("\n\n ERROR: indeterminate byte order");
0139         printf("\n \t %x %x %x %x", pf[0],pf[1],pf[2],pf[3]);
0140         return(UNKNOWN_ENDIAN);
0141   }
0142 }
0143 /* ************************************************** */
0144 void print_runtime_info(int argc, char *argv[])
0145 {  // print file header stuff
0146         printf("\n Command Line: ");
0147         for(int i=0; i<argc; i++) printf(" %s", argv[i]);
0148         // printf("\n Program %s Revision %f",  Prog_Name,Revision);
0149         printf("\n \t Copyright XXXX MCV");
0150         time_t t;
0151         t = time(NULL);
0152         printf("\n Run on %s\n",  ctime(&t) );
0153 }
0154 /* ****************************************************************** */
0155 void allocate_pbuffer()
0156 {
0157    pbuffer = (char *)malloc(MAX_BUFFER_SIZE * sizeof(char) +2);
0158       if(pbuffer == NULL)
0159       {
0160                   printf("\n Error Allocating Memory Buffer");
0161                   exit(EXIT_FAILURE);
0162    }
0163 }
0164 /* ***************************************************************** */
0165 /* *********************************************************************** */
0166 int advance(char *istr, int *sval, int len)
0167 {                           /* advances past white-space in file */
0168       while( !isspace(istr[*sval]) && (*sval < len) )
0169             *sval+=1; /* advance to space */
0170       while( isspace(istr[*sval]) && (*sval < len) )
0171             *sval+=1; /* advance to next thing */
0172       if(*sval > len) return(FAIL); /* return 0 when fails */
0173       return (OK);
0174 }
0175 /* ********************************************************************** */
0176 int my_isascii( int c )
0177 {
0178    return( !(c < 0 || c > 0177) );
0179 }
0180 /* ********************************************************************* */
0181 int clean_name(char *name)
0182 {
0183    int len = strlen(name);
0184    char *tname = (char *) calloc(len+1, sizeof(char));
0185    if(tname == NULL)
0186    {
0187       eprintf("\n ERROR: memory allocation error");
0188       return(FAIL);
0189    }
0190    strcpy(tname, name);
0191    if(clean_name(tname, name)!= OK)
0192    {
0193       eprintf("\n ERROR: cleaning Name");
0194       return(FAIL);
0195    }
0196    free(tname);
0197    return(OK);
0198 }
0199 /* ********************************************************************* */
0200 int clean_name(char *tmp_path, char *opath)
0201 {
0202    /* remove spaces, *'s, :'s &'s and commas from the name */
0203    int len = strlen(tmp_path);
0204    int o_index=0;
0205    for(int i=0; i<len; i++)
0206    {
0207       if( isspace(tmp_path[i] ) )
0208       {
0209           if( o_index &&              // add a _ if not first char
0210               opath[o_index-1] != '_' ) // and if previous char not a _
0211          opath[o_index++] = '_';
0212       }
0213       else
0214       if( my_isascii( tmp_path[i] ) &&
0215           tmp_path[i] != '&'   &&
0216           tmp_path[i] != ','   &&
0217           tmp_path[i] != '*'   &&
0218           tmp_path[i] != '/'   &&
0219           tmp_path[i] != ':' )
0220           opath[o_index++] = tmp_path[i];
0221    }
0222    opath[o_index] = '\0'; /* terminate the string */
0223 
0224    return(OK);
0225 }
0226 /* *********************************************************************** */
0227 FILE *open_file(char *filename, const char*extension, const char *access)
0228 {
0229   char string[MAX_STR_LEN];
0230   FILE *strm = NULL;
0231 
0232   if(filename[0]=='\0')
0233    {
0234       printf("\n INPUT FILENAME (%s) > ",access);
0235       //(MACG)-Wunused-result fgets(string,MAX_STR_LEN,stdin);
0236       char* dummy = fgets(string, MAX_STR_LEN, stdin);
0237       (void) dummy;  //(MACG) no -Wunused-variable
0238       sscanf(string,"%s",filename);
0239       printf(" FILE %s opened \n", filename);
0240    }
0241    int len=strlen(filename);
0242 
0243    if( len + strlen(extension) >= MAX_STR_LEN)
0244    {
0245       printf("\n ERROR: String Length  of %s.%s Exceeds Maximum",
0246               filename, extension);
0247       return(NULL);
0248    }
0249 
0250    // char *filename1 = new(char[len+strlen(extension)+1]);
0251 
0252    const int filenameLength = len+strlen(extension)+1;
0253    //(MACG)-Wvla char *filename1 = new(char[filenameLength]);
0254    char *filename1 = new char[filenameLength];
0255 
0256    strcpy(filename1,filename); // temp filename for appending extension
0257 
0258    /* check if file name has .extension    */
0259    /* if it does not, add .extension to it */
0260    int i=len-1;
0261    while(i > 0 && filename[i--] != '.');
0262    //   printf("\n Comparing %s to %s", extension, filename+i+1);
0263    if(strcmp(extension, filename+i+1)  )
0264       strcat(filename1,extension);
0265    if( (strm = fopen(filename1, access) ) == NULL )
0266    {
0267       printf("\n ERROR OPENING FILE %s (mode %s)", filename1,access);
0268    }
0269    //(MACG)-Wvla delete(filename1);
0270    delete[] filename1;
0271    return(strm);
0272 }
0273 /* *********************************************************************** */
0274 int ok_check(void)                          /* GETS RESPONSE FROM USER      */
0275 {                                           /* IF OK TO DO SOMETHING        */
0276    char reply[MAX_STR_LEN];                 /* RETURNS 1 ONLY IF REPLY Y    */
0277                                             /* OR y ELSE RETURNS 0          */
0278    //(MACG)-Wunused-result fgets(reply,MAX_STR_LEN,stdin);
0279    char* dummy = fgets(reply,MAX_STR_LEN,stdin);
0280    (void) dummy;  //(MACG) no -Wunused-variable
0281    if(  ( strncmp(reply,"Y",1)==0 )||
0282    ( strncmp(reply,"y",1)==0 ))
0283      return(1);
0284    return(0);
0285 }
0286 /* ***********************************************************************  */
0287 int ok_checks(char *string)
0288 {
0289    printf("\n %s", string);
0290    return(ok_check());
0291 }
0292 /* ********************************************************************** */
0293 #include <stdarg.h> // for va function
0294 int pprintf(char *fmt, ... )
0295 {
0296   va_list  argptr;         /* Argument list pointer   */
0297   char str[MAX_STR_LEN];           /* Buffer to build sting into   */
0298   int cnt;            /* Result of SPRINTF for return */
0299   va_start( argptr, fmt );      /* Initialize va_ functions   */
0300   //(MACG) Apple SDK deprecated:
0301   //cnt = vsprintf( str, fmt, argptr );   /* prints string to buffer   */
0302   cnt = vsnprintf(str, MAX_STR_LEN, fmt, argptr);  /* prints string to buffer */
0303   if(str[0] == '\0') return(0);
0304   printf("%s", str);   /* Send  to screen */
0305   if(pbuffer != NULL && strlen(pbuffer) + strlen(str) < MAX_BUFFER_SIZE)
0306      strcat(pbuffer,str);
0307   else
0308      printf("\n ERROR: pbuffer is full");
0309   va_end( argptr );         /* Close va_ functions      */
0310   return( cnt );         /* Return the conversion count   */
0311 }
0312 /* *********************************************************************** */
0313 /* eprintf: for buffering error reports, writes error messages to a buffer,
0314    and, also can echo them to the screen (if set at compile time)
0315    at first instance, allocates memory for the error buffer              */
0316 static char *ebuffer = NULL;
0317 int eprintf(const char *fmt, ... )
0318 {
0319   va_list  argptr;         /* Argument list pointer   */
0320   char str[MAX_STR_LEN];           /* Buffer to build sting into   */
0321   int cnt;            /* Result of SPRINTF for return */
0322   va_start( argptr, fmt );      /* Initialize va_ functions   */
0323   //(MACG) Apple SDK deprecated:
0324   //cnt = vsprintf( str, fmt, argptr );   /* prints string to buffer   */
0325   cnt = vsnprintf(str, MAX_STR_LEN, fmt, argptr);  /* prints string to buffer */
0326   if(str[0] == '\0') return(0);
0327 
0328   if(eprintf_mode==ON)
0329      fprintf(stdout,"%s", str);   /* Send  to screen */
0330 
0331   // allocate memory for the error message
0332   int ilen = 0;
0333   if(ebuffer != NULL)
0334   {
0335      ilen+=strlen(ebuffer);
0336      ebuffer = (char *) realloc(ebuffer, (ilen+strlen(str)+1)*sizeof(char));
0337   }
0338   else
0339      ebuffer = (char *) calloc(ilen+strlen(str)+1,sizeof(char));
0340 
0341   if(ebuffer == NULL)
0342   {
0343      printf("\n ERROR: ebuffer cannot be allocated in eprintf");
0344   }
0345   else
0346      strcat(ebuffer,str);
0347   va_end( argptr );         /* Close va_ functions      */
0348   return( cnt );         /* Return the conversion count   */
0349 }
0350 int view_errors(void)
0351 {
0352    printf("\n%s\n",ebuffer);
0353    return(OK);
0354 }
0355 /* ************************************************************************** */
0356 int latex_string(char *string, char *nstring)
0357 {
0358   // adds \\ in front of % so % will show up in the comment when printed
0359   // with LaTeX
0360    // must change all %'s to \% for latex output
0361    // also, must do the same for $, &, # _  { and }
0362    int len = strlen(string);
0363    int sval=0;
0364    int j;
0365    while(isspace(string[sval]) )sval++; // remove space from start of string
0366    while(isspace(string[len-1]))len--; // remove space from end to string
0367 
0368    j=0;
0369    for(int i=sval;i<len;i++)
0370    {
0371       if(string[i]=='%' ||
0372          string[i]=='$' ||
0373          string[i]=='&' ||
0374          string[i]=='#' ||
0375          string[i]=='_' ||
0376          string[i]=='{' ||
0377          string[i]=='}' )
0378       {
0379          nstring[j++]='\\';
0380       }
0381       else
0382       if(string[i]=='<' ||
0383          string[i]=='>' )
0384       {
0385          nstring[j++]='$';
0386       }
0387       nstring[j++] = string[i];
0388       if(string[i]=='<' ||
0389       string[i]=='>' )
0390       {
0391          nstring[j++]='$';
0392       }
0393    }
0394    nstring[j]='\0';
0395 /*   printf("\n string: %s", string);
0396    printf("\n nstring: %d %s",j, nstring); */
0397    return(OK);
0398 }
0399 /* ************************************************************************** */
0400 float interpolate(float xh, float xl, float xm, float yh, float yl)
0401 {
0402   return(yh - (xh-xm)/(xh-xl)*(yh-yl));
0403 }
0404 /* *********************************************************************** */
0405 // #define DEBUG_ARRAY
0406 /* ********************************************************************** */
0407 int array_read(char *in_string, float *array, int max_array)
0408 {
0409    char delimeter_string[MAX_STR_LEN];
0410    //(MACG) Apple SDK deprecated:
0411    // sprintf(delimeter_string," ,\t"); /* spaces, commas, and tabs */
0412    int cnt =
0413      snprintf(delimeter_string,MAX_STR_LEN," ,\t"); /* spaces, commas, and tabs */
0414    (void) cnt; //(MACG) silent -Wunused-result and -Wunused-variable
0415 
0416    char *p; /* pointer to string read in */
0417    p = strtok(in_string,delimeter_string);
0418    int i=0;
0419    if(p!=NULL)
0420    {
0421       array[i++]=(float)atof(p); /* get the first value */
0422       // if( sscanf(p,"%f",&array[i]) == 1) i++; // sscanf rounds values....
0423       do{             /* get remaining values */
0424          p = strtok(NULL,delimeter_string);
0425          if(p!=NULL)
0426          {
0427          //array[i++] = atof(p);
0428             if( sscanf(p,"%f",&array[i]) == 1) i++;
0429             // printf("\n Got Value of %f", array[i-1]);
0430          }
0431       }while(p!=NULL && i < max_array);
0432    }
0433 
0434 #ifdef DEBUG_ARRAY
0435    printf("\n atof %d", i);
0436    for(int j=0; j<i; j++) {
0437      //     array[j] = 0.0001*round(1000.0*array[j]);
0438       printf("\n i = %d, %f",j,array[j]);
0439    }
0440 #endif
0441    return(i);
0442 
0443 }
0444 int array_read(FILE *istrm, float *array, int max_array)
0445 {
0446    // reads in an array of floats from a single line of istrm
0447    // returns the number of elements read in
0448 
0449    char in_string[MAX_STR_LEN];
0450 
0451    if(fgets(in_string, MAX_STR_LEN, istrm) == NULL ) return(FAIL);
0452 #ifdef DEBUG_ARRAY
0453    printf("\nInput String\n %s", in_string);
0454 #endif
0455 
0456    int slen = strlen(in_string);
0457 
0458    int k=0;
0459    while(isspace(in_string[k]) && k < slen) k++;
0460    if(slen==0 || !(isdigit(in_string[k])
0461               ||    in_string[k] == '.'
0462               ||    in_string[k] == '+'
0463               ||    in_string[k] == '-'))
0464    {
0465       return(0); // skip blank and non-numerical lines
0466    }
0467    int nread = array_read(in_string,array,max_array);
0468 
0469    return(nread);  // return the number of elements read
0470 }
0471 /* ********************************************************************** */
0472 int copy(char *SourceFile, char *DestinationFile)
0473 {
0474   /* Copies sourceFile to destination file like unix cp command */
0475   FILE *sStream = fopen(SourceFile, "rb");
0476   if(sStream == NULL)
0477   {
0478      perror("\n ERROR: copy: ");
0479      printf("\n ERROR: copy: Opening Source File %s",SourceFile);return(FAIL);
0480   }
0481   FILE *dStream = fopen(DestinationFile,"wb");
0482   if(dStream == NULL)
0483   {
0484      perror("\n ERROR: copy:");
0485      printf("\n ERROR: copy: Opening Destination File %s",DestinationFile);return(FAIL);
0486   }
0487   char buffer[1000];
0488   int nRead;
0489   do{
0490      nRead = fread(buffer, sizeof(char), 1000, sStream);
0491      if( nRead )
0492         fwrite(buffer, sizeof(char), nRead, dStream);
0493   }while( !feof(sStream) && !ferror(dStream) && !ferror(sStream) );
0494   if(ferror(sStream) || ferror(dStream) )
0495   {
0496      perror("ERROR: Copy: ");
0497      printf("\n ERROR: source %s, destination %s", SourceFile, DestinationFile);
0498      return(FAIL);
0499   }
0500   fclose(sStream);
0501   fclose(dStream);
0502   return(OK);
0503 }
0504 /* ********************************************************************** */
0505 /* ************************************************************************************ */
0506 int readBinaryDataFromFile(FILE *iStream, int nItemsToRead, float **arrayToRead, int swab_flag)
0507 {
0508   // Reads binary data to stream, swab's if requested (1=swab, 0=don't swab)
0509   // Swab if needed...Put swabbed results in different array so no need to "unswab" when done
0510   // Allocate memory to read array into
0511    float *inputArray;
0512    inputArray = (float *) calloc(nItemsToRead,sizeof(float));
0513    if(inputArray == NULL) {
0514       printf("\n ERROR: Allocating memory for inputArray in readBinaryDataFromFile");
0515       return(FAIL);
0516    }
0517    if(OK != readBinaryDataFromFile(iStream, nItemsToRead, inputArray, swab_flag)) {
0518      printf("\n ERROR: Reading binary data from file"); return(FAIL);
0519    }
0520    *arrayToRead = inputArray;
0521    return(OK);
0522 }
0523 /* ************************************************************************************ */
0524 int readBinaryDataFromFile(FILE *iStream, int nItemsToRead, float *inputArray, int swab_flag)
0525 {
0526   // Reads binary data to stream, swab's if requested (1=swab, 0=don't swab)
0527   // Swab if needed...Put swabbed results in different array so no need to "unswab" when done
0528   // Allocate memory to read array into
0529    // Read in the array....
0530    int nRead=fread(inputArray,sizeof(float),nItemsToRead, iStream);
0531    if(nRead != nItemsToRead) {
0532      eprintf("\n ERROR: Wrong number read from file (%d %d)\n",
0533            nRead, nItemsToRead); return(FAIL);
0534    }
0535    // Check if need to swab the data
0536    if(swab_flag) // swab if swab_flag != 0
0537    {
0538       for(int index=0; index<nItemsToRead;index++)
0539       {
0540          inputArray[index] = reverse_float_byte_order( inputArray[index] );
0541       }
0542    }
0543    return(OK);
0544 }
0545 /* ***************************************************************************************** */
0546 int writeBinaryFile(char *binaryFileName, int nItemsToWrite, float *arrayToWrite, int swab_flag)
0547 {
0548    FILE *outputStream= fopen(binaryFileName,"wb");
0549    if (outputStream == NULL) {
0550      eprintf("\n ERROR: Cannot open file %s for writing\n",binaryFileName); return(FAIL);
0551    }
0552    if(OK != writeBinaryDataToFile(outputStream, nItemsToWrite, arrayToWrite, swab_flag) )
0553    {
0554      eprintf("\n ERROR: Writing Binary File"); return(FAIL);
0555    }
0556    fclose(outputStream);
0557    return(OK);
0558 }
0559 /* ************************************************************************************ */
0560 int writeBinaryDataToFile(FILE *outputStream, int nItemsToWrite, float *arrayToWrite, int swab_flag)
0561 {
0562   // Writes binary data to stream, swab's if requested (1=swab, 0=don't swab)
0563    // Swab if needed...Put swabbed results in different array so no need to "unswab" when done
0564    float *swabbedArray;
0565    if(swab_flag) // swab if swab_flag != 0
0566    {
0567       //
0568       swabbedArray = (float *) calloc(nItemsToWrite,sizeof(float));
0569       if(swabbedArray == NULL) {
0570       eprintf("\n ERROR: Allocating memory for swabbedArray in writeBinaryFile");
0571         return(FAIL);
0572       }
0573       for(int index=0; index<nItemsToWrite;index++)
0574       {
0575          swabbedArray[index] = reverse_float_byte_order( arrayToWrite[index] );
0576       }
0577    } else {
0578      swabbedArray = arrayToWrite;
0579    }
0580    // Check that writing positive number of items
0581    if(nItemsToWrite < 0 )
0582    {
0583      eprintf("\n ERROR: writeBinaryDataToFile: nItemsToWrite= %d < 0", nItemsToWrite); return(FAIL);
0584    }
0585    // Write the dose distribution
0586    int nWrite=fwrite(swabbedArray,sizeof(float),nItemsToWrite, outputStream);
0587    if(nWrite != nItemsToWrite) {
0588      eprintf("\n ERROR: Wrong number written to file (%d %d)\n",
0589            nWrite, nItemsToWrite); return(FAIL);
0590    }
0591    // free swabbedArray if it was allocated here
0592    if(swab_flag) {
0593      free(swabbedArray);
0594    }
0595    return(OK);
0596 }
0597 /* ***************************************************************************************************** */
0598 
0599 int writeBigEndianBinaryFile(char *binaryFileName,  int nItemsToWrite, float *arrayToWrite)
0600 {
0601    // Pinnacle doses always written in BIG_ENDIAN format... Check if need to swab.....
0602    int swab_flag = 0;
0603    switch( (check_byte_order()) )
0604    {
0605       case BIG_ENDIAN:
0606          break;
0607       case LITTLE_ENDIAN:
0608          swab_flag=1;
0609         break;
0610       default:
0611          eprintf("\n ERROR: Indeterminate Byte Order\n");
0612          return(FAIL);
0613    }
0614    if(OK != writeBinaryFile(binaryFileName, nItemsToWrite, arrayToWrite, swab_flag) )
0615    {
0616      printf("\n ERROR: Writing dose file %s", binaryFileName); return(FAIL);
0617    }
0618    return(OK);
0619 }
0620 /* ***************************************************************************************************** */
0621 int writeLittleEndianBinaryFile(char *binaryFileName,  int nItemsToWrite, float *arrayToWrite)
0622 {
0623    // Pinnacle doses always written in BIG_ENDIAN format... Check if need to swab.....
0624    int swab_flag = 0;
0625    switch( (check_byte_order()) )
0626    {
0627       case BIG_ENDIAN:
0628       swab_flag=1;
0629          break;
0630       case LITTLE_ENDIAN:
0631         break;
0632       default:
0633          eprintf("\n ERROR: Indeterminate Byte Order\n");
0634          return(FAIL);
0635    }
0636    if(OK != writeBinaryFile(binaryFileName, nItemsToWrite, arrayToWrite, swab_flag) )
0637    {
0638      printf("\n ERROR: Writing dose file %s", binaryFileName); return(FAIL);
0639    }
0640    return(OK);
0641 }
0642 /* ***************************************************************************************************** */
0643 char *strnset(char *s, int ch, size_t n)
0644 {  /* mimic strnset command in dos/ os2/ win / ... */
0645    for(int i=0; i< (int) n; i++)
0646    {
0647      if(s[i] == STR_NULL ) return(s); // return when find null
0648       s[i] = ch;
0649    }
0650    return(s);
0651 }
0652 int get_string(FILE *fspec, char *string)
0653 {
0654 #ifdef DEBUG
0655   int rvalue=fget_c_string(string, MAX_STR_LEN, fspec);
0656   printf("\n fget_c_string returns %s", string);
0657   return(rvalue);
0658 #else
0659   return(fget_c_string(string, MAX_STR_LEN, fspec));
0660 #endif
0661 }
0662 #define REWIND_STREAM 100
0663 /* ************************************************************************** */
0664 int fget_c_string(char *string, int Max_Str_Len, FILE *fspec)
0665 {
0666    /* gets a string from the input and removes comments from it */
0667    /* allows comments in standard "c" syntax,
0668            starting with / *
0669       ending with  * /  */
0670    /* also allows c++ type comments, // causes rest of line to be skipped */
0671 
0672    int check;
0673    char comment_start[4]="/*";  /* signals start of comment */
0674    char comment_stop[4]="*/";   /* signals end of comment   */
0675    int clen; /* length of string for start/stop*/
0676    int ilen; /* length of input string */
0677    char *istring; /* input string */
0678    int olen; /* location on output string */
0679    int icnt; /* location on string */
0680 
0681    //   int n_pass = 0; /* Number of passes through the file looking for a value */
0682 
0683    olen = 0;
0684    /* allocate memory for input string */
0685    istring = (char *)calloc(Max_Str_Len,sizeof(char));
0686    if(istring == NULL)
0687    {
0688       printf("\n ERROR: Allocating memory for input string if fget_c_string");
0689       return(FAIL);
0690    }
0691    strnset(string,'\0',Max_Str_Len); /* null entire output string */
0692    strnset(istring,'\0',Max_Str_Len); /* null entire input string */
0693 
0694 #ifdef DEBUG
0695    printf ("\n --------------fget_c_string");
0696 #endif
0697    clen = strlen(comment_start);
0698    /* read in the line, verify that it exists */
0699    do{
0700       /* read in a line from the file */
0701       while(fgets(istring, Max_Str_Len, fspec) == NULL) /* output warning if not a valid read */
0702       {
0703 #ifdef DEBUG
0704         printf("\n istring: %s", istring);
0705 #endif
0706 #ifdef ALLOW_REWIND
0707    if(n_pass) /* if already gone through file once looking for value, quit */
0708 #endif
0709    {
0710 #ifdef DEBUG
0711            //  printf ("\n***End of Input File in get_string, closing");
0712 #endif
0713            //  printf ("\nERROR: Reading File : End of File On Read ");
0714            // fclose(fspec);
0715            free(istring);
0716            return(FAIL);
0717         }
0718 #ifdef ALLOW_REWIND
0719         n_pass++;      /* increment the number of times through the file */
0720         rewind(fspec); /* rewind to the beginning of the file */
0721         free(istring);
0722         return(REWIND_STREAM);
0723 #endif
0724       }
0725 #ifdef DEBUG
0726         printf("\n istring: %s", istring);
0727 #endif
0728       ilen = strlen(istring); /* length of input string */
0729       istring[ilen]='\0'; /* null terminate the string */
0730       if(ilen < clen) /* not possible to have comment on the line */
0731       {               /* so output the string as is */
0732          strcpy(string,istring);
0733          olen = strlen(string);
0734       }
0735       else
0736       {
0737         /* strip comments out of input string */
0738         icnt=0;
0739         do{
0740           check = 1;
0741           if(icnt < ilen - clen)  /* make sure have enough characters for start of comment */
0742              check = strncmp(istring+icnt,comment_start,clen); /* check if start of comment */
0743           if(check == 0) /* comment found for standard c syntax */
0744           {
0745             /* find end of comment */
0746             icnt+=clen; /* advance past comment delimeter */
0747             clen=strlen(comment_stop); /* get length of end of comment delimiter */
0748             /* look for end of comment till end of string */
0749             do{
0750                check = 1;
0751                if(icnt < ilen - clen)  /* make sure have enough characters for end of comment */
0752                   check = strncmp(istring+icnt, comment_stop,clen);
0753                if(check != 0)  /* if not end of comment */
0754                {
0755                   icnt++; /* increment location on string */
0756                   if(icnt>ilen) /* if advance past end of string, get a new one */
0757                   {
0758                      if(fgets(istring, Max_Str_Len, fspec) == NULL) /* output warning if not a valid read */
0759                      {
0760                         printf ("\nERROR: Reading File, looking for end of comment %s",comment_stop);
0761                         // fclose(fspec);
0762                         free(istring);
0763                         return(FAIL);
0764                      }
0765                      ilen = strlen(istring); /* get length of this new string */
0766                      /* null terminate the string */
0767                      istring[ilen]='\0';
0768                      icnt = 0; /* reset the counter to the start of the string */
0769                   }
0770                }
0771                else
0772                {
0773                   icnt+=clen; /* advance past comment delimiter */
0774                }
0775             }while(check != 0); /* end of comment found */
0776           }  /* end if */
0777           else /* check if comment is in c++ format */
0778           {
0779              check = strncmp(istring+icnt, "//",2);
0780              if(check == 0) /* c++ style comment found */
0781              {  /* skip till end of string */
0782                 icnt = ilen;
0783                 string[olen++]='\n';
0784                 string[olen]='\0';
0785              }
0786              else /* is a valid character for the string */
0787              {
0788                 string[olen++] = istring[icnt++]; /* append value to the string */
0789                 string[olen]='\0';
0790              }
0791           }
0792         }while(icnt < ilen          &&    /* do till end of string */
0793                olen < Max_Str_Len); /* and output string not too long */
0794         /* check for only carriage return (should have been caught above) */
0795         if(olen == 1 && string[0] == '\n') olen = 0;
0796 
0797       }  /* end else */
0798    }while(olen == 0); /* do till read in a string */
0799    if(olen == Max_Str_Len)
0800    {
0801       printf ("\nERROR: Input line too long");
0802       // fclose(fspec);
0803       free(istring);
0804       return(FAIL);
0805    }
0806    free(istring);
0807    return(OK);
0808 }