TPCCLIB
Loading...
Searching...
No Matches
libtpcmisc.h File Reference

Header file for libtpcmisc. More...

#include "tpcclibConfig.h"
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <stdint.h>
#include <unistd.h>

Go to the source code of this file.

Data Structures

struct  IFT_KEY_AND_VALUE
 
struct  IFT
 
struct  INT_list
 
struct  INTEGER_LIST
 
struct  STR_TOKEN_LIST
 

Macros

#define BRANCHING_O   0.999
 
#define BRANCHING_C   0.998
 
#define BRANCHING_Cu64   0.174
 
#define BRANCHING_N   0.998
 
#define BRANCHING_F   0.967
 
#define BRANCHING_Ge   0.891
 
#define BRANCHING_Ga   0.891
 
#define BRANCHING_Rb   0.950
 
#define HL_O15   2.05 /* 123 s */
 
#define HL_N13   10.0
 
#define HL_C11   20.4
 
#define HL_F18   109.8
 
#define HL_Ge68   396000.0 /* 275 d */
 
#define HL_Ga68   68.0
 
#define HL_Br75   98.0
 
#define HL_Br76   978.33 /* 58700 s */
 
#define HL_Cu62   9.7 /* 582 s */
 
#define HL_Cu64   762.018 /* 12.7003 h */
 
#define HL_Fe52   4980.0
 
#define HL_Na22   1368000.0
 
#define HL_O14   1.1818
 
#define HL_Rb82   1.25 /* 75 s */
 
#define HL_Zn62   558.0
 
#define HL_I124   6013.44 /* 4.176 */
 
#define M_LN2   0.69314718055994530942
 
#define MAX_UNITS_LEN   31
 
#define MAX_REGIONNAME_LEN   20
 
#define MAX_REGIONSUBNAME_LEN   6
 
#define MAX_STUDYNR_LEN   255
 

Enumerations

enum  {
  TPCISOT_BR_75 , TPCISOT_BR_76 , TPCISOT_CU_62 , TPCISOT_CU_64 ,
  TPCISOT_FE_52 , TPCISOT_GA_68 , TPCISOT_GE_68 , TPCISOT_NA_22 ,
  TPCISOT_RB_82 , TPCISOT_ZN_62 , TPCISOT_F_18 , TPCISOT_C_11 ,
  TPCISOT_N_13 , TPCISOT_O_15 , TPCISOT_O_14 , TPCISOT_I_124 ,
  TPCISOT_UNKNOWN
}
 
enum  {
  CUNIT_UNKNOWN , CUNIT_CPS , CUNIT_COUNTS , CUNIT_KBQ_PER_ML ,
  CUNIT_SEC_KBQ_PER_ML , CUNIT_PER_SEC , CUNIT_PER_MIN , CUNIT_ML_PER_ML ,
  CUNIT_ML_PER_DL , CUNIT_ML_PER_ML_PER_MIN , CUNIT_ML_PER_DL_PER_MIN , CUNIT_UNITLESS ,
  CUNIT_NCI_PER_ML , CUNIT_MBQ_PER_ML , CUNIT_BQ_PER_ML , CUNIT_UCI_PER_ML ,
  CUNIT_UMOL_PER_MIN_PER_100G , CUNIT_MG_PER_MIN_PER_100G , CUNIT_UMOL_PER_MIN_PER_DL , CUNIT_MG_PER_MIN_PER_DL ,
  CUNIT_PERCENTAGE , CUNIT_KCPS , CUNIT_MIN_KBQ_PER_ML , CUNIT_BQ ,
  CUNIT_KBQ , CUNIT_MBQ , CUNIT_GBQ , CUNIT_NCI ,
  CUNIT_UCI , CUNIT_MCI , CUNIT_PID , CUNIT_PIDM ,
  CUNIT_PIDV , CUNIT_G_PER_ML , CUNIT_ML_PER_G , CUNIT_HU
}
 
enum  {
  TUNIT_UNKNOWN , TUNIT_SEC , TUNIT_MIN , TUNIT_UM ,
  TUNIT_MM , TUNIT_CM , TUNIT_M , TUNIT_HOUR ,
  TUNIT_MONTH , TUNIT_YEAR , TUNIT_MSEC
}
 
enum  {
  IFT_OK , IFT_FAULT , IFT_NOMEMORY , IFT_CANNOTREAD ,
  IFT_CANNOTWRITE , IFT_UNKNOWNFORMAT , IFT_KEYNOTFOUND , IFT_NODATA ,
  IFT_VALUENOTFOUND
}
 

Functions

int backupExistingFile (char *filename, char *backup_ext, char *status)
 
int fileCopy (char *filename1, char *filename2, char *status)
 
float branchingFraction (int isotope)
 
struct tm * gmtime_r (const time_t *t, struct tm *tm)
 Convert time_t to GMT struct tm.
 
struct tm * localtime_r (const time_t *t, struct tm *tm)
 Convert time_t to local time in struct tm.
 
time_t timegm (struct tm *tm)
 Inverse of gmtime, converting struct tm to time_t.
 
char * ctime_r_int (const time_t *t, char *buf)
 Convert calendard time t into a null-terminated string of the form YYYY-MM-DD hh:mm:ss, with length of 19 characters and the null.
 
int isdate (char *str)
 
int isdate2 (char *str, char *intdate)
 
int isdate3 (char *str, char *intdate)
 
int isdate4 (int dateint, int *year, int *month, int *day)
 
int istime (char *str)
 
int isdatetime (char *str, char *intdate)
 
int get_datetime (char *str, struct tm *date, int verbose)
 
int get_date (char *str, struct tm *date)
 
long int math_div (long int a, long int b)
 
int isleapyear (long int year)
 
long int leaps_between (long int year1, long int year2)
 
void time_to_tm (time_t totalsecs, int offset, struct tm *result)
 
double tmDifference (struct tm *tm1, struct tm *tm0)
 
void tmAdd (int s, struct tm *d)
 
int dec_comma_is (char *str)
 
int dec_separator (char *str)
 
void dec_separator_change (char *str, int decsep)
 
double atof_dpi (char *str)
 
int dec_nr (char *str)
 
int atof_with_check (char *double_as_string, double *result_value)
 
char * strPtrToNextValue (char *str, char **nxtp)
 
int atoi_with_check (const char *int_as_string, int *result_value)
 
void filenameRmPath (char *s)
 
int filenameRmExtension (char *s)
 
void filenameRmExtensions (char *s)
 
int fnmatch (const char *fname, const char *key)
 
int fncasematch (const char *fname, const char *key)
 
char * filenameGetExtension (char *s)
 Get the last extension of a filename.
 
char * filenameGetExtensions (char *s)
 Get all extensions of a filename.
 
char * hlIsotopeCode (int isotope)
 
double hlFromIsotope (char *isocode)
 
double hl2lambda (double halflife)
 
double hlLambda2factor (double lambda, double frametime, double framedur)
 
float hlLambda2factor_float (float lambda, float frametime, float framedur)
 
char * hlCorrectIsotopeCode (char *isocode)
 
int hlIsotopeFromHalflife (double halflife)
 
const char * libpet_idcrypt_version (void)
 
int id_crypt (const char *string, const char *key, char *out, int decrypt)
 
void iftSetStatus (IFT *ift, int status)
 
void iftInit (IFT *ift)
 
void iftEmpty (IFT *ift)
 
int iftPut (IFT *ift, char *key, char *value, char *cmt_type, int verbose)
 
int iftPutDouble (IFT *ift, char *key, double value, char *cmt_type, int verbose)
 
int iftRead (IFT *ift, char *filename, int is_key_required, int verbose)
 
char * iftReadValue (char *filename, char *keystr, int verbose)
 
int iftWriteItem (IFT *ift, int item, FILE *fp, int verbose)
 
int iftWrite (IFT *ift, char *filename, int verbose)
 
int defRead (IFT *ift, char *filename, int verbose)
 
int iftGet (IFT *ift, char *key, int verbose)
 
int iftGetNth (IFT *ift, char *key, int n, int verbose)
 
int iftFindNthKey (IFT *ift, char *str, int n, int verbose)
 
int iftFindNthValue (IFT *ift, char *str, int n, int verbose)
 
int iftGetKeyNr (IFT *ift, const char *key, int verbose)
 
int iftGetFrom (IFT *ift, int si, const char *key, int verbose)
 
int iftGetFullmatchFrom (IFT *ift, int si, const char *key, const char *value, int verbose)
 
int iftGetFloatValue (IFT *ift, int si, const char *key, float *value, int verbose)
 
int iftGetDoubleValue (IFT *ift, int si, const char *key, double *value, int verbose)
 
int iftGetIntValue (IFT *ift, int si, const char *key, int *value, int verbose)
 
int iftDeleteItem (IFT *ift, int item, int verbose)
 
int iftReplaceNthValue (IFT *ift, int item, char *value, int verbose)
 
int iftdup (IFT *ift1, IFT *ift2, int verbose)
 
void intInit (INT_list *list)
 
void intEmpty (INT_list *list)
 
int intExpand (char *text, INT_list *list)
 
INT_list intMerge (INT_list *list1, INT_list *list2)
 
int _intexadd (INT_list *list, int a)
 
int integerListInit (INTEGER_LIST *l)
 
int integerListEmpty (INTEGER_LIST *l)
 
int integerListAdd (INTEGER_LIST *l, int v, int ifnew)
 
int integerListSort (INTEGER_LIST *l)
 
int integerListAddFromString (const char *s1, const char *s2, INTEGER_LIST *l, const int ifnew)
 
int integerListExpandFromString (const char *s1, const char *s2, INTEGER_LIST *l, const int ifnew)
 
int temp_roundf (float e)
 
int petCunitId (const char *unit)
 
int petTunitId (const char *timeunit)
 
char * petCunit (int cunit)
 
char * petTunit (int tunit)
 
int cunitFromFilename (char *fname)
 
int tpcProcessStdOptions (const char *s, int *print_usage, int *print_version, int *verbose_level)
 
void tpcProgramName (const char *program, int version, int copyright, char *prname, int n)
 
void tpcPrintUsage (const char *program, char *text[], FILE *fp)
 
int tpcHtmlUsage (const char *program, char *text[], const char *path)
 
void tpcPrintBuild (const char *program, FILE *fp)
 
char * strstr_noquotation (const char *str1, const char *str2)
 
int strnCopyClean (char *str1, const char *str2, int maxlen)
 
void str_token_list_init (STR_TOKEN_LIST *lst)
 
void str_token_list_empty (STR_TOKEN_LIST *lst)
 
int str_token_list_add (STR_TOKEN_LIST *lst, char *new_item)
 
int str_token_list_del (STR_TOKEN_LIST *lst, int item)
 
int str_token_list_read (const char *filename, STR_TOKEN_LIST *lst)
 
int textfileReadLines (const char *filename, STR_TOKEN_LIST *lst)
 
int readStrtokens (const char *filename, char ***toklist)
 
int asciiCommentLine (const char *line, int *cont)
 
int rnameSplit (char *rname, char *name1, char *name2, char *name3, int max_name_len)
 
int rnameMatch (char *rname, int rnr, char *test_str)
 
int rnameRmDots (char *rname1, char *rname2)
 
int rnameCatenate (char *rname, int max_rname_len, char *name1, char *name2, char *name3, char space)
 
int roinameExists (char *roiname)
 Verifies whether TAC name exists or not.
 
int strTokenNr (const char *str1, const char *str2)
 
int strTokenNCpy (const char *str1, const char *str2, int i, char *str3, int count)
 
char * strTokenDup (const char *s1, const char *s2, int *next)
 
int strChrCount (const char *str1, const char *str2)
 
int strUppercaseCount (const char *s)
 
void strReplaceChar (char *str, char c1, char c2)
 
size_t strnlen (const char *s, size_t n)
 
size_t strlcat (char *dst, const char *src, size_t dstsize)
 
size_t strlcpy (char *dst, const char *src, size_t dstsize)
 
char * strcasestr (const char *haystack, const char *needle)
 
int strncpyCleanSpaces (char *s1, const char *s2, int maxlen)
 
int strCleanSpaces (char *s)
 
char * strEncodeForXML (const char *s)
 
void strCleanForXML (char *s)
 
int studynr_in_fname (char *fname, char *studynr)
 
int studynr_from_fname (char *fname, char *studynr)
 
int studynr_from_fname2 (char *fname, char *studynr, int force)
 
int studynr_match (char *studynr1, char *studynr2)
 
int studynr_validity_check2 (char *studynr, int zero_ok)
 
int studynr_validity_check (char *studynr)
 
int studynr_rm_zeroes (char *studynr)
 
int studynr_to_lowercase (char *studynr)
 
int little_endian ()
 
void swap (void *orig, void *new, int size)
 
void swabip (void *buf, long long int size)
 
void swawbip (void *buf, long long int size)
 
void swawip (void *buf, long long int size)
 
void printf32bits (void *buf)
 
int doubleMatch (const double v1, const double v2, const double lim)
 
int doubleMatchRel (const double v1, const double v2, const double lim)
 
double doubleMachEps ()
 
void doubleCopy (double *t, double *s, const unsigned int n)
 
unsigned int doubleMaxIndex (double *a, const unsigned int n)
 
double doubleSum (double *a, const unsigned int n)
 
double doubleMean (double *a, const unsigned int n)
 
int doubleSpanPositives (double *a, const int n)
 
int doubleCSpanPositives (double *a, const int n)
 
double inverfc (double x)
 
void statSortDouble (double *data, unsigned int n, int order)
 
void statSortFloat (float *data, unsigned int n, int order)
 

Detailed Description

Header file for libtpcmisc.

Author
Vesa Oikonen

Definition in file libtpcmisc.h.

Macro Definition Documentation

◆ BRANCHING_C

#define BRANCHING_C   0.998

Isotope branching ratio

Definition at line 28 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_Cu64

#define BRANCHING_Cu64   0.174

Isotope branching ratio

Definition at line 30 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_F

#define BRANCHING_F   0.967

Isotope branching ratio

Definition at line 34 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_Ga

#define BRANCHING_Ga   0.891

Isotope branching ratio

Definition at line 38 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_Ge

#define BRANCHING_Ge   0.891

Isotope branching ratio

Definition at line 36 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_N

#define BRANCHING_N   0.998

Isotope branching ratio

Definition at line 32 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_O

#define BRANCHING_O   0.999

Isotope branching ratio

Definition at line 26 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ BRANCHING_Rb

#define BRANCHING_Rb   0.950

Isotope branching ratio

Definition at line 40 of file libtpcmisc.h.

Referenced by branchingFraction().

◆ HL_Br75

#define HL_Br75   98.0

Isotope halflife in minutes; not verified from the reference

Definition at line 58 of file libtpcmisc.h.

◆ HL_Br76

#define HL_Br76   978.33 /* 58700 s */

Isotope halflife in minutes; not verified from the reference

Definition at line 60 of file libtpcmisc.h.

◆ HL_C11

#define HL_C11   20.4

Isotope halflife in minutes

Definition at line 47 of file libtpcmisc.h.

◆ HL_Cu62

#define HL_Cu62   9.7 /* 582 s */

Isotope halflife in minutes; not verified from the reference

Definition at line 62 of file libtpcmisc.h.

◆ HL_Cu64

#define HL_Cu64   762.018 /* 12.7003 h */

Isotope halflife in minutes; not verified from the reference

Definition at line 64 of file libtpcmisc.h.

◆ HL_F18

#define HL_F18   109.8

Isotope halflife in minutes

Definition at line 49 of file libtpcmisc.h.

◆ HL_Fe52

#define HL_Fe52   4980.0

Isotope halflife in minutes; not verified from the reference

Definition at line 66 of file libtpcmisc.h.

◆ HL_Ga68

#define HL_Ga68   68.0

Isotope halflife in minutes

Definition at line 53 of file libtpcmisc.h.

◆ HL_Ge68

#define HL_Ge68   396000.0 /* 275 d */

Isotope halflife in minutes

Definition at line 51 of file libtpcmisc.h.

◆ HL_I124

#define HL_I124   6013.44 /* 4.176 */

Isotope halflife in minutes; not verified from the reference

Definition at line 76 of file libtpcmisc.h.

◆ HL_N13

#define HL_N13   10.0

Isotope halflife in minutes

Definition at line 45 of file libtpcmisc.h.

◆ HL_Na22

#define HL_Na22   1368000.0

Isotope halflife in minutes; not verified from the reference

Definition at line 68 of file libtpcmisc.h.

◆ HL_O14

#define HL_O14   1.1818

Isotope halflife in minutes; not verified from the reference

Definition at line 70 of file libtpcmisc.h.

◆ HL_O15

#define HL_O15   2.05 /* 123 s */

Isotope halflife in minutes

Definition at line 43 of file libtpcmisc.h.

◆ HL_Rb82

#define HL_Rb82   1.25 /* 75 s */

Isotope halflife in minutes; not verified from the reference

Definition at line 72 of file libtpcmisc.h.

◆ HL_Zn62

#define HL_Zn62   558.0

Isotope halflife in minutes; not verified from the reference

Definition at line 74 of file libtpcmisc.h.

◆ M_LN2

#define M_LN2   0.69314718055994530942

ln(2)

Definition at line 90 of file libtpcmisc.h.

Referenced by hl2lambda(), and plasma_to_blood_ratio().

◆ MAX_REGIONNAME_LEN

◆ MAX_REGIONSUBNAME_LEN

#define MAX_REGIONSUBNAME_LEN   6

◆ MAX_STUDYNR_LEN

◆ MAX_UNITS_LEN

#define MAX_UNITS_LEN   31

Max length of units string (+1), based on ECAT7 format

Definition at line 95 of file libtpcmisc.h.

Referenced by cptReadOne(), dftAllocateWithIMG(), and dftGetPmodTitle().

Enumeration Type Documentation

◆ anonymous enum

anonymous enum

isotope_code

Definition at line 79 of file libtpcmisc.h.

79 {
80 TPCISOT_BR_75, TPCISOT_BR_76, TPCISOT_CU_62, TPCISOT_CU_64,
81 TPCISOT_FE_52, TPCISOT_GA_68, TPCISOT_GE_68, TPCISOT_NA_22,
82 TPCISOT_RB_82, TPCISOT_ZN_62, TPCISOT_F_18, TPCISOT_C_11,
83 TPCISOT_N_13, TPCISOT_O_15, TPCISOT_O_14, TPCISOT_I_124,
84 TPCISOT_UNKNOWN
85};

◆ anonymous enum

anonymous enum

Data y units

Definition at line 99 of file libtpcmisc.h.

99 {
100 /* 0 */ CUNIT_UNKNOWN,
101 /* 1 */ CUNIT_CPS,
102 /* 2 */ CUNIT_COUNTS,
103 /* 3 */ CUNIT_KBQ_PER_ML,
104 /* 4 */ CUNIT_SEC_KBQ_PER_ML,
105 /* 5 */ CUNIT_PER_SEC,
106 /* 6 */ CUNIT_PER_MIN,
107 /* 7 */ CUNIT_ML_PER_ML,
108 /* 8 */ CUNIT_ML_PER_DL,
109 /* 9 */ CUNIT_ML_PER_ML_PER_MIN,
110 /* 10 */ CUNIT_ML_PER_DL_PER_MIN,
111 /* 11 */ CUNIT_UNITLESS,
112 /* 12 */ CUNIT_NCI_PER_ML,
113 /* 13 */ CUNIT_MBQ_PER_ML,
114 /* 14 */ CUNIT_BQ_PER_ML,
115 /* 15 */ CUNIT_UCI_PER_ML,
116 /* 16 */ CUNIT_UMOL_PER_MIN_PER_100G,
117 /* 17 */ CUNIT_MG_PER_MIN_PER_100G,
118 /* 18 */ CUNIT_UMOL_PER_MIN_PER_DL,
119 /* 19 */ CUNIT_MG_PER_MIN_PER_DL,
120 /* 20 */ CUNIT_PERCENTAGE,
121 /* 21 */ CUNIT_KCPS,
122 /* 22 */ CUNIT_MIN_KBQ_PER_ML,
123 /* 23 */ CUNIT_BQ,
124 /* 24 */ CUNIT_KBQ,
125 /* 25 */ CUNIT_MBQ,
126 /* 26 */ CUNIT_GBQ,
127 /* 27 */ CUNIT_NCI,
128 /* 28 */ CUNIT_UCI,
129 /* 29 */ CUNIT_MCI,
130 /* 30 */ CUNIT_PID,
131 /* 31 */ CUNIT_PIDM,
132 /* 32 */ CUNIT_PIDV,
133 /* 33 */ CUNIT_G_PER_ML, // SUV unit
134 /* 34 */ CUNIT_ML_PER_G, // SUV unit
135 /* 35 */ CUNIT_HU // Hounsfield unit
136};

◆ anonymous enum

anonymous enum

Data x units

Definition at line 138 of file libtpcmisc.h.

138 {
139 /* 0 */ TUNIT_UNKNOWN,
140 /* 1 */ TUNIT_SEC,
141 /* 2 */ TUNIT_MIN,
142 /* 3 */ TUNIT_UM,
143 /* 4 */ TUNIT_MM,
144 /* 5 */ TUNIT_CM,
145 /* 6 */ TUNIT_M,
146 /* 7 */ TUNIT_HOUR,
147 /* 8 */ TUNIT_MONTH,
148 /* 9 */ TUNIT_YEAR,
149 /* 10 */ TUNIT_MSEC
150};

◆ anonymous enum

anonymous enum

Definitions for ift status message

Definition at line 249 of file libtpcmisc.h.

249 {IFT_OK, IFT_FAULT, IFT_NOMEMORY, IFT_CANNOTREAD, IFT_CANNOTWRITE,
250 IFT_UNKNOWNFORMAT, IFT_KEYNOTFOUND, IFT_NODATA, IFT_VALUENOTFOUND};

Function Documentation

◆ _intexadd()

int _intexadd ( INT_list * list,
int a )
extern

int _intexadd(int *list, int a) ; local function. Deprecated.

Parameters
list
a

Definition at line 92 of file intex.c.

92 {
93 int i, j, n;
94
95 /* Check if list is yet empty */
96 if(list->nr==0) {
97 list->i=(int*)malloc(sizeof(int)); if(list->i==NULL) return(-1);
98 /* Put the first integer to list and return */
99 list->nr=1; list->i[0]=a; return(1);
100 }
101 n=list->nr;
102 /* Check through the existing list */
103 for(i=0; i<n; i++) {
104 /* if it already is listed, just return */
105 if(list->i[i]==a) return(0);
106 /* make room for this integer */
107 list->i=(int*)realloc(list->i, (n+1)*sizeof(int)); if(list==NULL) return(-1);
108 if(list->i[i]>a) {for(j=n-1; j>=i; j--) list->i[j+1]=list->i[j]; break;}
109 }
110 list->i[i]=a; list->nr=n+1;
111 return(1);
112}
int * i
Definition libtpcmisc.h:322

Referenced by intExpand().

◆ asciiCommentLine()

int asciiCommentLine ( const char * line,
int * cont )
extern

Check if ASCII text line starts with comment character '#'. Comment character is searched from the first non-space character (space characters here include spaces and tabs).

Returns
1 if this is comment line and 0 if not.
Author
Vesa Oikonen
Parameters
linePointer to string containing one line of ASCII text file
contOptional pointer which is set to the index of line where the first non-space character after the comment character starts. If line does not start with comment character, then this will point to the first non-space character of the line.
Enter NULL if not needed.

Definition at line 246 of file readfile.c.

255 {
256 if(cont!=NULL) *cont=0;
257 if(line==NULL) return 0;
258 char *cptr=(char*)line;
259 int i=strspn(cptr, " \t"); cptr+=i; if(cont!=NULL) *cont=i;
260 if(*cptr!='#') return 0;
261 if(cont==NULL) return 1;
262 cptr++; i=strspn(cptr, " \t"); *cont+=(i+1);
263 return 1;
264}

Referenced by sifRead().

◆ atof_dpi()

double atof_dpi ( char * str)
extern

Replacement of atof(), which works whether string contains decimal dots or decimal commas. Possible commas are replaced by dots in the argument string.

Returns
Returns the double float.
Parameters
strPointer to string (not modified).

Definition at line 59 of file decpoint.c.

62 {
63 char *cptr;
64 double f;
65
66 if(str==NULL) return(nan(""));
67 /* If string contains a dot, then use atof directly */
68 if(strchr(str, '.')!=NULL) return(atof(str));
69 /* Otherwise, convert all commas to dots */
70 //while((cptr=strchr(str, ','))!=NULL) *cptr='.';
71 cptr=strchr(str, ','); if(cptr!=NULL) *cptr='.';
72 f=atof(str); if(cptr!=NULL) *cptr=',';
73 return(f);
74}

Referenced by atof_with_check(), csv2dft_a(), csv2dft_b(), dft_fill_hdr_from_IFT(), dftRead(), fitRead(), and resRead().

◆ atof_with_check()

int atof_with_check ( char * double_as_string,
double * result_value )
extern

Converts a string to float using atof(), but if its return value is zero this function checks that argument string actually contains a number. Result value is set to NaN if string was not valid value. Both decimal point and comma are accepted.

Returns
Returns 0 if successful, and 1 in case of an error.
Parameters
double_as_stringString which is converted to a double; not modified
result_valuePointer to the double float; enter NULL, if not needed

Definition at line 107 of file decpoint.c.

112 {
113 char* cptr;
114 double f;
115
116 if(result_value!=NULL) *result_value=nan("");
117 if(double_as_string==NULL) return(1);
118 f=atof_dpi(double_as_string);
119 if(f!=0.0) {if(result_value!=NULL) *result_value=f; return(0);}
120 cptr=double_as_string;
121 while(*cptr!=0 && (*cptr=='+' || *cptr=='-' || *cptr==' ')) cptr++;
122 if(*cptr=='0') {if(result_value!=NULL) *result_value=f; return(0);}
123 return(1);
124}
double atof_dpi(char *str)
Definition decpoint.c:59

Referenced by csv2dft_linkset(), csv2dft_mat(), dftRead(), and readEcat931Calibrationfile().

◆ atoi_with_check()

int atoi_with_check ( const char * int_as_string,
int * result_value )
extern

Converts a string to integer (int) using atoi, but this function verifies that argument string actually contains an integer number. String must end in NULL character. Exponentials are not accepted. Result value is set to 0 if string was not valid value.

Returns
Returns 0 if successful, and 1 in case of an error.
Parameters
int_as_stringString which is converted to a int; not modified
result_valuePointer to the int; enter NULL, if not needed

Definition at line 238 of file decpoint.c.

243 {
244 int i, len;
245
246 if(result_value!=NULL) *result_value=0;
247 if(int_as_string==NULL) return(1);
248 len=strlen(int_as_string); if(len<1) return(1);
249 /* First character can be + or - */
250 i=strspn(int_as_string, "+-");
251 if(i>1) return(1);
252 if(i==1 && len==1) return(1);
253 /* Check that (rest of) characters are digits */
254 for( ; i<len; i++) if(!isdigit(int_as_string[i])) return(1);
255 /* Convert to int */
256 if(result_value!=NULL) *result_value=atoi(int_as_string);
257 return(0);
258}

Referenced by integerListAddFromString(), and pxlRead().

◆ backupExistingFile()

int backupExistingFile ( char * filename,
char * backup_ext,
char * status )
extern

Check if specified file exists; rename existing file to a backup file. If also backup file exists, then remove that.

Returns
Returns 0, if successful, and <>0 in case of an error.
Parameters
filenameName of file which, if it exists, is renamed to a backup file
backup_extExtension for backup file; NULL will set the default ".bak" extension.
statusPointer to a string (allocated for at least 64 chars) where error message or other execution status will be written; enter NULL, if not needed

Definition at line 14 of file backup.c.

22 {
23 char bakfile[FILENAME_MAX];
24 int ret;
25
26 // Check the input
27 if(filename==NULL || strlen(filename)<1) {
28 if(status!=NULL) sprintf(status, "invalid filename");
29 return 1;
30 }
31
32 // Check if file exists; if not then no need to make any backup
33 if(access(filename, 0) == -1) {
34 if(status!=NULL) sprintf(status, "file does not pre-exist");
35 return 0;
36 }
37 // Create filename for the backup file
38 strlcpy(bakfile, filename, FILENAME_MAX);
39 if(backup_ext==NULL) strlcat(bakfile, ".bak", FILENAME_MAX);
40 else strlcat(bakfile, backup_ext, FILENAME_MAX);
41 // If also backup file exists, then just delete it
42 if(access(bakfile, 0) != -1) {
43 ret=remove(bakfile);
44 if(ret!=0) {
45 if(status!=NULL) sprintf(status, "cannot delete previous backup file");
46 return 3;
47 }
48 }
49 // Rename file
50 ret=rename(filename, bakfile);
51 if(ret!=0) {
52 if(status!=NULL) sprintf(status, "cannot rename file as backup");
53 return 5;
54 }
55 if(status!=NULL) sprintf(status, "file renamed as backup");
56 return 0;
57}
size_t strlcpy(char *dst, const char *src, size_t dstsize)
Definition strext.c:245
size_t strlcat(char *dst, const char *src, size_t dstsize)
Definition strext.c:206

Referenced by dftWrite(), fitWrite(), plot_fit_svg(), plot_fitrange_svg(), plot_svg(), plotdata(), and resWrite().

◆ branchingFraction()

float branchingFraction ( int isotope)

Branching fraction for specified isotope.

Returns
Returns the branching factor, or 0 in case branching fraction is unknown.
Parameters
isotopeIsotope code; see hlIsotopeFromHalflife()

Definition at line 14 of file branch.c.

17 {
18 float bf=0.0;
19 switch(isotope) {
20 case TPCISOT_CU_64: bf=BRANCHING_Cu64; break;
21 case TPCISOT_GA_68: bf=BRANCHING_Ga; break;
22 case TPCISOT_GE_68: bf=BRANCHING_Ge; break;
23 case TPCISOT_RB_82: bf=BRANCHING_Rb; break;
24 case TPCISOT_F_18: bf=BRANCHING_F; break;
25 case TPCISOT_C_11: bf=BRANCHING_C; break;
26 case TPCISOT_N_13: bf=BRANCHING_N; break;
27 case TPCISOT_O_15: bf=BRANCHING_O; break;
28 case TPCISOT_BR_75:
29 case TPCISOT_BR_76:
30 case TPCISOT_CU_62:
31 case TPCISOT_FE_52:
32 case TPCISOT_NA_22:
33 case TPCISOT_O_14:
34 case TPCISOT_I_124:
35 case TPCISOT_ZN_62:
36 case TPCISOT_UNKNOWN:
37 default: bf=0.0;
38 }
39 return(bf);
40}
#define BRANCHING_O
Definition libtpcmisc.h:26
#define BRANCHING_Rb
Definition libtpcmisc.h:40
#define BRANCHING_C
Definition libtpcmisc.h:28
#define BRANCHING_F
Definition libtpcmisc.h:34
#define BRANCHING_Cu64
Definition libtpcmisc.h:30
#define BRANCHING_Ge
Definition libtpcmisc.h:36
#define BRANCHING_N
Definition libtpcmisc.h:32
#define BRANCHING_Ga
Definition libtpcmisc.h:38

Referenced by hrrtMakeCalHdr(), imgBranchingCorrection(), and imgGetMicropetHeader().

◆ ctime_r_int()

char * ctime_r_int ( const time_t * t,
char * buf )
extern

Convert calendard time t into a null-terminated string of the form YYYY-MM-DD hh:mm:ss, with length of 19 characters and the null.

This is a replacement of the thread-safe ctime_r function which converts to date and time in english format.

Author
Vesa Oikonen
Returns
Returns pointer to the string, or null in case of an error.
Parameters
tPointer to calendar time ; do not give pointer to int here, like &e7mhdr.scan_start_time
bufPointer to string where the date and time will be written. It must be pre-allocated for at least 20 characters.

Definition at line 110 of file datetime.c.

117 {
118 if(buf==NULL) return(NULL);
119 buf[0]=(char)0;
120 struct tm tm;
121 if(!gmtime_r(t, &tm)) return(NULL);
122 if(!strftime(buf, 20, "%Y-%m-%d %H:%M:%S", &tm)) return(NULL);
123 return(buf);
124}
struct tm * gmtime_r(const time_t *t, struct tm *tm)
Convert time_t to GMT struct tm.
Definition datetime.c:22

Referenced by atnMake(), ecat7MHeaderToIFT(), ecat7PrintMainheader(), fitWrite(), imgGetEcat63MHeader(), imgInfo(), imgSetEcat63MHeader(), imgWriteEcat63Frame(), imgWriteFrame(), plotdata(), resWrite(), resWriteHTML_table(), and sifPrint().

◆ cunitFromFilename()

int cunitFromFilename ( char * fname)
extern

Tries to find calibration unit from filename.

Returns
Returns CUNIT, which is CUNIT_UNKNOWN if not successful.
See also
petCunitId, petTunitId, petCunit, petTunit
Parameters
fnamePointer to file name, where calibration unit is tried to be found.

Definition at line 242 of file petunits.c.

245 {
246 char *cptr;
247
248 if(fname==NULL || strlen(fname)<3) return CUNIT_UNKNOWN;
249 for(int i=0; i<2; i++) {
250 if(i==0) /* First, look in the extension */
251 {cptr=strrchr(fname, '.'); if(cptr==NULL) {cptr=fname; i++;}}
252 else /* Then, look into whole filename */
253 cptr=fname;
254 if(strcasestr(cptr, "KBQ")!=NULL) return CUNIT_KBQ_PER_ML;
255 if(strcasestr(cptr, "MBQ")!=NULL) return CUNIT_MBQ_PER_ML;
256 if(strcasestr(cptr, "BQ")!=NULL) return CUNIT_BQ_PER_ML;
257 if(strcasestr(cptr, "NCI")!=NULL) return CUNIT_NCI_PER_ML;
258 if(strcasestr(cptr, "KCPS")!=NULL) return CUNIT_KCPS;
259 if(strcasestr(cptr, "CPS")!=NULL) return CUNIT_CPS;
260 }
261 return CUNIT_UNKNOWN;
262}
char * strcasestr(const char *haystack, const char *needle)
Definition strext.c:279

◆ dec_comma_is()

int dec_comma_is ( char * str)
extern

Checks whether argument string contains a decimal comma instead of dot.

Returns
Returns 1 if decimal comma is found and 0 if not found.
Parameters
strPointer to string (not modified).

Definition at line 14 of file decpoint.c.

17 {
18 if(strchr(str, '.')!=NULL) return(0);
19 if(strchr(str, ',')!=NULL) return(1);
20 return(0);
21}

◆ dec_nr()

int dec_nr ( char * str)
extern

Returns the number of decimal places in the argument string, representing a floating point value. String can contain either decimal dots or commas.

Definition at line 81 of file decpoint.c.

82{
83 char *cptr;
84 int n;
85
86 if(str==NULL) return 0;
87 /* Find the first dot or comma, but stop with E */
88 cptr=str;
89 while(*cptr!='.' && *cptr!=',') {
90 if(*cptr==(char)0 || *cptr=='E' || *cptr=='e') return 0;
91 cptr++;
92 }
93 if(*cptr==(char)0 || (*cptr!='.' && *cptr!=',')) return 0;
94 /* Calculate the number of digits that follows */
95 cptr++; n=0; while(cptr!=NULL && isdigit(*cptr)) {n++; cptr++;}
96 return n;
97}

Referenced by dftRead().

◆ dec_separator()

int dec_separator ( char * str)
extern

Checks whether argument string contains a decimal comma or dot, or neither.

Returns
Returns 0, if neither is found, 1 if dot, and 2 if comma is found.
Parameters
strPointer to string (not modified).

Definition at line 28 of file decpoint.c.

31 {
32 if(strchr(str, '.')!=NULL) return(1);
33 if(strchr(str, ',')!=NULL) return(2);
34 return(0);
35}

◆ dec_separator_change()

void dec_separator_change ( char * str,
int decsep )
extern

Convert the first decimal separator to comma or dot, as required.

Parameters
strPointer to string (modified when necessary).
decsepRequested decimal separator: 0=dot, 1=comma.

Definition at line 40 of file decpoint.c.

45 {
46 char *cptr;
47 cptr=strchr(str, '.'); if(cptr!=NULL && decsep==1) {*cptr=','; return;}
48 cptr=strchr(str, ','); if(cptr!=NULL && decsep==0) {*cptr='.'; return;}
49 return;
50}

◆ defRead()

int defRead ( IFT * ift,
char * filename,
int verbose )
extern

Read definition file, for example microPET header file, into IFT structure.

Returns
Returns 0 if ok. Sets ift->status.
See also
iftWrite, iftRead
Parameters
iftPointer to initiated but empty IFT
filenameInput filename
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 321 of file iftfile.c.

328 {
329 int i, ret, nr=0, line=0, initial_key_nr=0, nonprintable=0;
330 char *allfile, *cptr, *key_ptr, *value_ptr, *cmt_ptr;
331 FILE *fp;
332
333 /* Check function input */
334 if(verbose>0) printf("%s(*ift, %s)\n", __func__, filename);
335 if(ift==NULL) return(1);
336 if(filename==NULL || strlen(filename)<1) {
337 iftSetStatus(ift, IFT_FAULT); return(1);
338 }
339 if(ift->keyNr>0) initial_key_nr=ift->keyNr;
340
341 /* Open file */
342 if(strcasecmp(filename, "stdin")==0) {
343 fp=stdin;
344 } else {
345 fp=fopen(filename, "r");
346 if(fp==NULL) {iftSetStatus(ift, IFT_CANNOTREAD); return(2);}
347 }
348
349 /* Get file size */
350 nr=nonprintable=0; while((ret=fgetc(fp))!=EOF) {
351 if(iscntrl(ret) && ret!=13 && ret!=10 && ret!=9) {
352 nonprintable=1; break;}
353 nr++;
354 }
355 if(nr<2) {
356 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
357 if(nonprintable>0) {
358 /* File contains non-printable characters; maybe binary file */
359 iftSetStatus(ift, IFT_UNKNOWNFORMAT);
360 } else {
361 /* File just din't have any content */
362 iftSetStatus(ift, IFT_NODATA);
363 }
364 return(3);
365 }
366 if(verbose>1) printf(" the size of file is %d bytes\n", nr);
367 if(nr>5000000) {
368 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
369 iftSetStatus(ift, IFT_UNKNOWNFORMAT); return(3);
370 }
371 rewind(fp);
372
373 /* Allocate memory for file contents */
374 allfile=(char*)malloc((nr+1)*sizeof(char));
375 if(allfile==NULL) {
376 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
377 iftSetStatus(ift, IFT_NOMEMORY); return(4);
378 }
379
380 /* Read file contents and close the file */
381 i=0; while((ret=fgetc(fp))!=EOF && i<nr) allfile[i++]=(char)ret;
382 allfile[i]=(char)0;
383 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
384
385 /* and then fill the list */
386 /* separate the first line */
387 cptr=strtok(allfile, "\n\r"); line=0;
388 do {
389 if(verbose>10) printf("line %d: '%s'\n", line, cptr);
390 /* Remove initial spaces and tabs */
391 i=strspn(cptr, " \t"); cptr+=i;
392 if(strlen(cptr)<1) {cptr=strtok(NULL, "\n\r"); continue;}
393 /* Check if line starts with a comment character */
394 if((cmt_ptr=strchr("#!;%", cptr[0]))!=NULL) {
395 /* save the whole line as a key */
396 key_ptr=cptr; value_ptr=NULL;
397 ret=iftPut(ift, key_ptr, value_ptr, " ", verbose-2);
398 if(ret) {
399 free(allfile); iftEmpty(ift); iftSetStatus(ift, IFT_FAULT);
400 return(10+ret);
401 }
402 /* separate the next line */
403 cptr=strtok(NULL, "\n\r"); line++;
404 continue;
405 }
406 if(verbose>11) printf(" line %d: '%s'\n", line, cptr);
407 /* Get the first line string representing key name */
408 key_ptr=cptr; cptr=strchr(cptr, ' ');
409 if(cptr!=NULL) {*cptr=(char)0; cptr++;}
410 /* Rest of the line is the key value */
411 if(cptr==NULL) value_ptr=NULL; else value_ptr=cptr;
412 ret=iftPut(ift, key_ptr, value_ptr, " ", verbose-2);
413 if(ret) {
414 free(allfile); iftEmpty(ift); iftSetStatus(ift, IFT_FAULT);
415 return(10+ret);
416 }
417 /* separate the next line */
418 cptr=strtok(NULL, "\n\r"); line++;
419 } while(cptr!=NULL);
420 free(allfile);
421
422 /* Did we actually get any data? */
423 if(ift->keyNr<=initial_key_nr) {iftSetStatus(ift, IFT_NODATA); return(7);}
424
425 /* Set parameter file type */
426 ift->type=4;
427
428 iftSetStatus(ift, IFT_OK);
429 return(0);
430}
int iftPut(IFT *ift, char *key, char *value, char *cmt_type, int verbose)
Definition ift.c:82
void iftEmpty(IFT *ift)
Definition ift.c:60
void iftSetStatus(IFT *ift, int status)
Definition ift.c:29
int type
Definition libtpcmisc.h:275
int keyNr
Definition libtpcmisc.h:270

Referenced by imgReadMicropetFrame(), and imgReadMicropetHeader().

◆ doubleCopy()

void doubleCopy ( double * t,
double * s,
const unsigned int n )
extern

Copy double values from the 2nd array to the first.

Parameters
tTarget array
sSource array
nLength of arrays

Definition at line 93 of file doubleutil.c.

100 {
101 unsigned int i;
102 if(t==NULL || s==NULL || n<1) return;
103 for(i=0; i<n; i++) t[i]=s[i];
104}

◆ doubleCSpanPositives()

int doubleCSpanPositives ( double * a,
const int n )
extern

Returns the length of array consisting of non-positive (<=0 and NaN) values.

Returns
Returns the index of first positive value in the given array.
See also
doubleSpanPositives
Parameters
aPointer to the array.
nLength of the array.

Definition at line 186 of file doubleutil.c.

191 {
192 if(a==NULL || n<1) return(0);
193 int i=0;
194 for(i=0; i<n; i++) if(a[i]>0.0) break;
195 return(i);
196}

◆ doubleMachEps()

double doubleMachEps ( )
extern

Estimates the machine epsilon, the upper bound on the relative error due to rounding in floating point arithmetic, within one order of magnitude of the true machine epsilon.

Standard C library should also have DBL_EPSILON in float.h.

Returns
Estimate of machine epsilon.
Author
Vesa Oikonen
See also
doubleMatchRel, doubleMatch

Definition at line 83 of file doubleutil.c.

84{
85 double macheps=1.0;
86 do {macheps/=2.0;} while((1.0+macheps/2.0)!=1.0);
87 return(macheps);
88}

Referenced by householder_transform().

◆ doubleMatch()

int doubleMatch ( const double v1,
const double v2,
const double lim )
extern

Verifies that given two doubles have the same value inside given limits.

Values are considered to match also if both are NaNs.

Returns
1 if match is found, and 0 if not.
Author
Vesa Oikonen
See also
doubleMatchRel, doubleMachEps
Parameters
v1First value
v2Second value
limLimit for absolute difference (if <0 then test will fail every time)

Definition at line 28 of file doubleutil.c.

35 {
36 if(isnan(v1) && isnan(v2)) return 1;
37 if(isnan(v1) || isnan(v2)) return 0;
38 if(v1==v2) return 1;
39 if(isnan(lim) || lim<0.0) return 0;
40 if(fabs(v1-v2)<=lim) return 1;
41 return 0;
42}

◆ doubleMatchRel()

int doubleMatchRel ( const double v1,
const double v2,
const double lim )
extern

Verifies that given two doubles have the same value inside given relative limit |2*(v1-v2)/(v1+v2)|.

Values are considered to match also if both are NaNs, but not if mean is zero (unless both are exactly zero).

Returns
1 if match is found, and 0 if not.
Author
Vesa Oikonen
See also
doubleMatch, doubleMachEps
Parameters
v1First value
v2Second value
limLimit for relative difference (if <0 then test will fail every time)

Definition at line 55 of file doubleutil.c.

62 {
63 if(isnan(v1) && isnan(v2)) return 1;
64 if(isnan(v1) || isnan(v2)) return 0;
65 if(v1==v2) return 1;
66 if(isnan(lim)) return 0;
67 double mean;
68 mean=0.5*(v1+v2); if(!isnormal(mean)) return 0;
69 if(fabs((v1-v2)/mean)<=lim) return 1;
70 return 0;
71}
int mean(double *x, double *y, int nr, double *xmean, double *xsd, double *ymean, double *ysd)
Definition pearson.c:341

◆ doubleMaxIndex()

unsigned int doubleMaxIndex ( double * a,
const unsigned int n )
extern

Find the maximum value in given double array.

Returns
The index [0..n-1] of maximum value in array; 0 is returned also in case of errors.
Parameters
aPointer to double array.
nLength of array.

Definition at line 111 of file doubleutil.c.

116 {
117 if(a==NULL || n<1) return(0);
118 unsigned int i, mi=0;
119 double mv=nan("");
120 for(i=0; i<n; i++) if(isnan(mv) || a[i]>mv) {mv=a[i]; mi=i;}
121 return(mi);
122}

◆ doubleMean()

double doubleMean ( double * a,
const unsigned int n )
extern

Calculate the mean of values in given double array.

Returns
The mean of array values, or NaN in case of an error.
See also
doubleSum
Parameters
aPointer to double array.
nLength of array.

Definition at line 148 of file doubleutil.c.

153 {
154 if(a==NULL || n<1) return(nan(""));
155 double s=0.0;
156 unsigned int i, ci=0;
157 for(i=0; i<n; i++) if(!isnan(a[i])) {ci++; s+=a[i];}
158 if(ci<1) return(nan(""));
159 return(s/(double)ci);
160}

◆ doubleSpanPositives()

int doubleSpanPositives ( double * a,
const int n )
extern

Returns the length of array consisting of only positive (>0 and not NaN) values.

Returns
Returns the index of first nonpositive value in the given array.
See also
doubleCSpanPositives
Parameters
aPointer to the array.
nLength of the array.

Definition at line 168 of file doubleutil.c.

173 {
174 if(a==NULL || n<1) return(0);
175 int i=0;
176 for(i=0; i<n; i++) if(!(a[i]>0.0)) break;
177 return(i);
178}

◆ doubleSum()

double doubleSum ( double * a,
const unsigned int n )
extern

Calculate the sum of values in given double array.

Returns
The sum of array values.
See also
doubleMean
Parameters
aPointer to double array.
nLength of array.

Definition at line 130 of file doubleutil.c.

135 {
136 double s=0.0;
137 if(a==NULL || n<1) return(s);
138 for(unsigned int i=0; i<n; i++) if(!isnan(a[i])) s+=a[i];
139 return(s);
140}

◆ fileCopy()

int fileCopy ( char * filename1,
char * filename2,
char * status )
extern

Copy file contents to another file. Existing file will be overwritten, to prevent it call backupExistingFile() before calling this function.

Returns
Returns 0 if successfull, otherwise >0.
Parameters
filename1Name of file to be copied
filename2Name of new file
statusPointer to a string (allocated for at least 64 chars) where error message or other execution status will be written; enter NULL, if not needed

Definition at line 65 of file backup.c.

73 {
74 FILE *from, *to;
75 char c;
76
77 // Check the input
78 if(filename1==NULL || filename2==NULL) {
79 if(status!=NULL) sprintf(status, "invalid filename");
80 return 1;
81 }
82 // Open the file1 for reading
83 if((from=fopen(filename1, "rb"))==NULL) {
84 if(status!=NULL) sprintf(status, "cannot open file for read");
85 return 2;
86 }
87 // Open file2 for writing
88 if((to=fopen(filename2, "wb"))==NULL) {
89 if(status!=NULL) sprintf(status, "cannot open file for write");
90 fclose(from); return 3;
91 }
92 // Copy the file
93 while(!feof(from)) {
94 c=fgetc(from);
95 if(ferror(from)) {
96 if(status!=NULL) sprintf(status, "cannot read from file");
97 fclose(from); fclose(to); (void)remove(filename2); return 4;
98 }
99 if(!feof(from)) fputc(c, to);
100 if(ferror(to)) {
101 if(status!=NULL) sprintf(status, "cannot write to file");
102 fclose(from); fclose(to); (void)remove(filename2); return 6;
103 }
104 }
105 // Close files
106 if(fclose(from)==EOF) {
107 if(status!=NULL) sprintf(status, "cannot close file");
108 fclose(to); return 7;
109 }
110 if(fclose(to)==EOF) {
111 if(status!=NULL) sprintf(status, "cannot close file");
112 return 8;
113 }
114 return 0;
115}

◆ filenameGetExtension()

char * filenameGetExtension ( char * s)
extern

Get the last extension of a filename.

Extension(s) in pathname are not searched for. Note that pointer points to the original string.

Returns
Pointer to the filename extension starting with '.', or NULL if no extension is found.
Parameters
sPointer to string; string is not edited here.

Definition at line 139 of file filename.c.

142 {
143 if(s==NULL || strlen(s)<1) return((char*)NULL);
144 /* Identify path */
145 char *pptr=strrchr(s, '/'); if(pptr==NULL) pptr=strrchr(s, '\\');
146 if(pptr==NULL) pptr=s; else pptr++;
147 /* Search for the last '.' after the path */
148 char *cptr=strrchr(pptr, '.'); if(cptr==NULL) return(cptr);
149 /* If filename starts with '.', that is not counted as extension */
150 if(strlen(pptr)==strlen(cptr)) return((char*)NULL);
151 return(cptr);
152}

◆ filenameGetExtensions()

char * filenameGetExtensions ( char * s)
extern

Get all extensions of a filename.

Extension(s) in pathname are not searched for. Note that pointer points to the original string.

Returns
Pointer to the filename extension starting with '.', or NULL if no extension is found.
Parameters
sPointer to string; string is not edited here.

Definition at line 164 of file filename.c.

167 {
168 if(s==NULL || strlen(s)<1) return((char*)NULL);
169 /* Identify path */
170 char *pptr=strrchr(s, '/'); if(pptr==NULL) pptr=strrchr(s, '\\');
171 if(pptr==NULL) pptr=s; else pptr++;
172 /* Search for the last '.' after the path, ignoring first character
173 in case filename starts with '.' */
174 char *cptr=strchr(pptr+1, '.');
175 return(cptr);
176}

◆ filenameRmExtension()

int filenameRmExtension ( char * s)
extern

Remove the last extension from file name.

Author
Vesa Oikonen
Returns
1 if extension was found (and removed), 0 if not.
Parameters
sPointer to string

Definition at line 34 of file filename.c.

37 {
38 if(s==NULL || strlen(s)<1) return(0);
39 char *cptr;
40 cptr=strrchr(s, '.'); if(cptr==NULL) return(0);
41 if(cptr[1]=='/' || cptr[1]=='\\') return(0);
42 *cptr=(char)0;
43 return(1);
44}

Referenced by filenameRmExtensions(), tpcHtmlUsage(), tpcPrintBuild(), tpcPrintUsage(), and tpcProgramName().

◆ filenameRmExtensions()

void filenameRmExtensions ( char * s)
extern

Remove all extensions from file name.

Author
Vesa Oikonen
Parameters
sPointer to string

Definition at line 51 of file filename.c.

54 {
55 if(s==NULL || strlen(s)<1) return;
56 while(filenameRmExtension(s)) {}
57 return;
58}
int filenameRmExtension(char *s)
Definition filename.c:34

◆ filenameRmPath()

void filenameRmPath ( char * s)
extern

Remove path from file name.

Author
Vesa Oikonen
Parameters
sPointer to string

Definition at line 13 of file filename.c.

16 {
17 if(s==NULL || strlen(s)<1) return;
18 char *cptr;
19 cptr=strrchr(s, '/'); if(cptr==NULL) cptr=strrchr(s, '\\');
20 if(cptr==NULL) return;
21 cptr++;
22 int i, n=strlen(cptr);
23 for(i=0; i<n; i++, cptr++) s[i]=*cptr;
24 s[i]=(char)0;
25 return;
26}

Referenced by tpcHtmlUsage(), tpcPrintBuild(), tpcPrintUsage(), and tpcProgramName().

◆ fncasematch()

int fncasematch ( const char * fname,
const char * key )
extern

Case-independent check whether string fname matches string key, which may contain wildcards ? and *.

Returns
1 if strings do match and 0 if not.
Parameters
fnamefilename that is evaluated
keykey string which may contain wildcards '?' and '*'

Definition at line 100 of file filename.c.

105 {
106 if(fname==NULL || key==NULL) return(0);
107 char *key_ptr=NULL, *fname_ptr=NULL;
108
109 while((*key)&&(*fname)) {
110 if((*key=='?')||(toupper((int)*key)==toupper((int)*fname))) {
111 key++; fname++;
112 } else if(*key=='*') {
113 if(toupper((int)*(key+1))==toupper((int)*fname)) {
114 key_ptr=(char*)key++; fname_ptr=(char*)fname+1;
115 } else {
116 fname++;
117 if(*(key+1)=='?') {key_ptr=(char*)key++; fname_ptr=(char*)fname;}
118 }
119 } else if((key_ptr!=NULL) && (*fname_ptr)) {
120 return(fnmatch(key_ptr, fname_ptr));
121 } else {
122 return(0);
123 }
124 }
125 if((*fname)&&(key_ptr!=NULL)) {return(fnmatch(key_ptr, fname_ptr));}
126 else {if(*key=='*') key++; return(toupper((int)*key)==toupper((int)*fname));}
127}
int fnmatch(const char *fname, const char *key)
Definition filename.c:66

Referenced by dftFormat(), dftWrite(), and rnameMatch().

◆ fnmatch()

int fnmatch ( const char * fname,
const char * key )
extern

Check if string fname matches string key, which may contain wildcards ? and *.

Returns
1 if strings do match and 0 if not.
Parameters
fnamefilename that is evaluated
keykey string which may contain wildcards '?' and '*'

Definition at line 66 of file filename.c.

71 {
72 if(fname==NULL || key==NULL) return(0);
73 char *key_ptr=NULL, *fname_ptr=NULL;
74
75 while((*key)&&(*fname)) {
76 if((*key=='?')||(*key==*fname)) {
77 key++; fname++;
78 } else if(*key=='*') {
79 if(*(key+1)==*fname) {key_ptr=(char*)key++; fname_ptr=(char*)fname+1;
80 } else {
81 fname++;
82 if(*(key+1)=='?') {key_ptr=(char*)key++; fname_ptr=(char*)fname;}
83 }
84 } else if((key_ptr!=NULL) && (*fname_ptr)) {
85 return(fnmatch(key_ptr, fname_ptr));
86 } else {
87 return(0);
88 }
89 }
90 if((*fname)&&(key_ptr!=NULL)) {return(fnmatch(key_ptr, fname_ptr));}
91 else {if(*key=='*') key++; return(*key==*fname);}
92}

Referenced by fncasematch(), and fnmatch().

◆ get_date()

int get_date ( char * str,
struct tm * date )
extern

Reads date from a standard string representation of date.

Returns
Returns 0 when successful, <>0 in case of an error.
Parameters
strPointer to string that contains date in one of the formats YYYY-MM-DD, DD/MM/YYYY, DD.MM.YYYY, DD/MM/YY, or DD.MM.YYYY. This string is not modified.
datePointer to allocated struct tm where the date is written

Definition at line 377 of file datetime.c.

384 {
385 char buf[32];
386 int ret, n, YYYY=0, MM=0, DD=0;
387
388 if(strlen(str)<8) return 1;
389 if((ret=isdate(str))<=0) {
390 strncpy(buf, str, 10); buf[10]=(char)0;
391 } else {
392 ret=isdate2(str, buf);
393 if(ret>0) ret=isdate3(str, buf);
394 }
395 if(ret>0) return 2;
396 n=sscanf(buf, "%d-%d-%d", &YYYY, &MM, &DD);
397 if(n!=3) return(3);
398 date->tm_year=YYYY-1900; date->tm_mday=DD; date->tm_mon=MM-1;
399 date->tm_hour=0; date->tm_min=0; date->tm_sec=0; date->tm_isdst=-1;
400 ret=strftime(buf, 32, "%Y-%m-%d %H:%M:%S", date);
401 if(ret==0) return(4);
402 return(0);
403}
int isdate2(char *str, char *intdate)
Definition datetime.c:168
int isdate(char *str)
Definition datetime.c:146
int isdate3(char *str, char *intdate)
Definition datetime.c:199

Referenced by resRead().

◆ get_datetime()

int get_datetime ( char * str,
struct tm * date,
int verbose )
extern

Reads time and date from a standard string representation of date and time.

Returns
Returns 0 when successful, <>0 in case of an error.
Parameters
strPointer to string that contains date and time in one of the formats YYYY-MM-DD hh:mm:ss, DD.MM.YYYY hh:mm:ss, or DD/MM/YY hh:mm:ss This string is not modified.
datePointer to allocated struct tm where date and time is written
verboseVerbose level; if <=0, then nothing is printed into stdout

Definition at line 322 of file datetime.c.

331 {
332 char buf[32];
333 int ret, n, YYYY=0, MM=0, DD=0, hh=0, mm=0, ss=0;
334
335 if(verbose>0) printf("get_datetime(%s)\n", str);
336 if(date==NULL) return(1);
337 ret=isdatetime(str, buf); if(ret!=0) return(ret);
338 n=sscanf(buf, "%d-%d-%d %d:%d:%d", &YYYY, &MM, &DD, &hh, &mm, &ss);
339 if(n!=6) return(40);
340 date->tm_year=YYYY-1900; date->tm_mday=DD; date->tm_mon=MM-1;
341 date->tm_hour=hh; date->tm_min=mm; date->tm_sec=ss;
342 date->tm_isdst=-1;
343#ifdef HAVE_TM_GMTOFF
344 date->tm_gmtoff=0L;
345#endif
346 if(verbose>2) {
347 printf("tm_mday=%d\n", date->tm_mday);
348 printf("tm_mon=%d\n", date->tm_mon);
349 printf("tm_year=%d\n", date->tm_year);
350 printf("tm_hour=%d\n", date->tm_hour);
351 time_t t=timegm(date);
352 printf(" tm_hour=%d\n", date->tm_hour);
353 printf("time_t=%ld\n", (long)t);
354 printf("time_t_int=%d\n", (int)t);
355 }
356// if(mktime(date)==-1 && date->tm_year<70) {
357 if(timegm(date)==-1 && date->tm_year<70) {
358 if(verbose>2) printf("tm_mday=%d\n", date->tm_mday);
359 if(verbose>1) printf("mktime() fails\n");
360 /* Date and time format was previously verified, so lets put
361 1970-01-01 01:00:00 instead */
362 date->tm_year=70; date->tm_mday=1; date->tm_mon=0;
363 date->tm_hour=1; date->tm_min=0; date->tm_sec=0;
364 date->tm_yday=0;
365 date->tm_isdst=-1;
366 mktime(date);
367 }
368 if(verbose>1) printf(" tm_hour=%d\n", date->tm_hour);
369 return(0);
370}
time_t timegm(struct tm *tm)
Inverse of gmtime, converting struct tm to time_t.
Definition datetime.c:69
int isdatetime(char *str, char *intdate)
Definition datetime.c:280

Referenced by ecat7EditMHeader(), fitRead(), resRead(), and selectEcat931Calibrationfile().

◆ gmtime_r()

struct tm * gmtime_r ( const time_t * t,
struct tm * tm )
extern

Convert time_t to GMT struct tm.

This version of gmtime_r function is here for systems (at least Windows) where it is not defined. Uses gmtime, which is threadsafe in Windows.

Returns
Pointer to struct tm, or null in case of an error.
Parameters
tPointer to time_t; do not give pointer to int here, like &e7mhdr.scan_start_time
tmPointer to struct tm, to be filled here

Definition at line 22 of file datetime.c.

28 {
29 struct tm *ltm=gmtime(t);
30 if(ltm==NULL || tm==NULL) return(NULL);
31 *tm=*ltm; tm->tm_isdst=-1;
32 return tm;
33}

Referenced by ctime_r_int(), ecat63AddImg(), ecat63WriteAllImg(), ecat7EditMHeader(), ecat7ReadMainheader(), ecatCopy7to63mainheader(), imgSetAnalyzeHeader(), imgSetEcat63MHeader(), imgWriteAnalyze(), res2ift(), sifWrite(), time_to_tm(), and timegm().

◆ hl2lambda()

double hl2lambda ( double halflife)
extern

Calculates the isotope lambda from specified halflife.

Parameters
halflifehalflife time value
Returns
A negative value is returned in case of error.

Definition at line 84 of file halflife.c.

84 {
85 if(halflife>0.0) return(M_LN2/halflife); else return(-1.0); // M_LN2=log(2.0)
86}
#define M_LN2
Definition libtpcmisc.h:90

Referenced by atnMake(), dftDecayCorrection(), img2sif(), imgDecayCorrection(), imgSetDecayCorrFactors(), and noiseSD4Simulation().

◆ hlCorrectIsotopeCode()

char * hlCorrectIsotopeCode ( char * isocode)
extern

Check that isotope code, e.g. F-18, is in valid format, containing '-' and in this order. Returns the correct isotope code.

Parameters
isocodePointer to string "C-11", "11c" etc; contents of this string is not changed, and this is not returned in any case
Returns
pointer to correct isotope code, and NULL if it was not valid and could not be corrected.

Definition at line 141 of file halflife.c.

141 {
142 int i, ok=0, n, mass_nr=0, ic_mass_nr=0;
143 char *cptr, atom[3], ic_atom[3];
144
145 /* Check, if isocode can be found in the list */
146 i=ok=0;
147 while(isotope_code[i]!=0) {
148 if(strcasecmp(isotope_code[i], isocode)==0) {
149 ok=1;
150 break;
151 }
152 i++;
153 }
154 if(ok==1) return(isotope_code[i]);
155
156 /* Try to figure out what it is */
157 /* Separate the atom name and mass number */
158 n=strcspn(isocode, "-1234567890");
159 if(n>2) { /* cannot be */
160 return(NULL);
161 } else if(n>0) { /* start with atom name */
162 strncpy(atom, isocode, n); atom[n]=(char)0;
163 mass_nr=atoi(isocode+n); if(mass_nr<0) mass_nr=-mass_nr;
164 } else { /* starts with mass number */
165 mass_nr=atoi(isocode);
166 cptr=isocode; while(isdigit((int)cptr[0])) cptr++;
167 if(strlen(cptr)>2) return(NULL);
168 strcpy(atom, cptr);
169 }
170 /* Check if it matches any of the listed isotopes */
171 i=ok=0;
172 while(isotope_code[i]!=0) {
173 /* Separate the atom name and mass number from the listed isotope */
174 n=strcspn(isotope_code[i], "-1234567890");
175 strncpy(ic_atom, isotope_code[i], n); ic_atom[n]=(char)0;
176 ic_mass_nr=atoi(isotope_code[i]+n+1);
177 /* Check the atom name */
178 if(strcasecmp(ic_atom, atom)!=0) {i++; continue;}
179 /* Check the mass number, if given */
180 if(mass_nr>0 && ic_mass_nr!=mass_nr) {i++; continue;}
181 /* Match was found! */
182 ok=1; break;
183 }
184 if(ok==1) return(isotope_code[i]); else return(NULL);
185}

Referenced by hlFromIsotope(), and sif2dft().

◆ hlFromIsotope()

double hlFromIsotope ( char * isocode)
extern

Identify the isotope from the specified isotope code string and return the halflife (min). This function checks the validity of the isotope string using hlCorrectIsotopeCode(), but does not change it in any way.

Returns
A negative value is returned in case of error.
Parameters
isocodePointer to string "C-11", "18f" etc. This argument is not changed.

Definition at line 55 of file halflife.c.

58 {
59 char *corrected_isocode;
60 int i = 0;
61 int ok = 0;
62
63 /* Validate the isotope string */
64 corrected_isocode=hlCorrectIsotopeCode(isocode);
65 if(corrected_isocode==NULL) return(-1.0);
66
67 /* Determine the isotope and return the half-life */
68 while(isotope_code[i]!=0) {
69 if(strcmp(isotope_code[i], corrected_isocode)==0) {ok=1; break;}
70 i++;
71 }
72 if(ok==1) return(isotope_halflife[i]);
73 else return(-2.0);
74}
char * hlCorrectIsotopeCode(char *isocode)
Definition halflife.c:141

Referenced by dftDecayCorrection(), imgReadAnalyzeHeader(), imgReadModelingData(), imgReadNiftiHeader(), noiseSD4SimulationFromDFT(), and sif2img().

◆ hlIsotopeCode()

char * hlIsotopeCode ( int isotope)
extern

Isotope code as a string, based on isotope list number.

Parameters
isotopeindex of PET isotope in the list in halflife.c
Returns
pointer to static string or "unknown".

Definition at line 36 of file halflife.c.

36 {
37 static char unknown_isotope[]="unknown";
38 int n=0;
39
40 while(isotope_code[n]!=0) n++;
41 if(isotope<0 || isotope>n-1) return(unknown_isotope);
42 else return(isotope_code[isotope]);
43}

Referenced by dftDecayCorrection(), and imgIsotope().

◆ hlIsotopeFromHalflife()

int hlIsotopeFromHalflife ( double halflife)
extern

Identify the isotope based on its halflife (in minutes).

Parameters
halflifeHalf-life in minutes
Returns
the isotope list number, or negative value if not identified.

Definition at line 195 of file halflife.c.

195 {
196 int i=0, ok=0;
197 if(halflife<=0.01) return(-1);
198 while(isotope_halflife[i]>0.0) {
199 if( fabs(halflife/isotope_halflife[i]-1.0)<0.05 ) {ok=1; break;}
200 i++;
201 }
202 if(ok==1) return(i);
203 else return(-2.0);
204}

Referenced by dftDecayCorrection(), imgBranchingCorrection(), and imgIsotope().

◆ hlLambda2factor()

double hlLambda2factor ( double lambda,
double frametime,
double framedur )
extern

Calculate the decay correction factor for specified isotope lambda.

Parameters
lambdaNegative lambda removes decay correction
frametimeFrame start time, or mid time if framedur<=0
framedurIf unknown, set <0 and give mid time for frametime
Returns
A negative value is returned in case of error.

Definition at line 98 of file halflife.c.

98 {
99 double cf, ff;
100
101 if(frametime<0) return(-1.0);
102 cf=exp(lambda*frametime);
103 if(framedur>1.0E-5) {
104 ff=fabs(lambda)*framedur/(1.0-exp(-fabs(lambda)*framedur));
105 if(lambda<0.0) cf/=ff; else cf*=ff;
106 }
107 return(cf);
108}

Referenced by atnMake(), dftDecayCorrection(), img2sif(), and noiseSD4Simulation().

◆ hlLambda2factor_float()

float hlLambda2factor_float ( float lambda,
float frametime,
float framedur )
extern

Calculate the decay correction factor for specified isotope lambda. Version for floats (mainly image data).

Parameters
lambdaNegative lambda removes decay correction
frametimeFrame start time, or mid time if framedur<=0
framedurIf unknown, set <0 and give mid time for frametime
Returns
A negative value is returned in case of error.

Definition at line 118 of file halflife.c.

118 {
119 float cf, ff;
120
121 if(frametime<0) return(-1.0);
122 cf=exp(lambda*frametime);
123 if(framedur>1.0E-5) {
124 ff=fabs(lambda)*framedur/(1.0-exp(-fabs(lambda)*framedur));
125 if(lambda<0.0) cf/=ff; else cf*=ff;
126 }
127 return(cf);
128}

Referenced by imgDecayCorrection(), and imgSetDecayCorrFactors().

◆ id_crypt()

int id_crypt ( const char * string,
const char * key,
char * out,
int decrypt )
extern

Scramble characters in ASCII range 32-126 using the Vigenere Cipher. Other characters are discarded.

Returns
Returns 0 if successful
Parameters
stringOriginal string to be encrypted/decrypted
keyKeyword string
outEncrypted/decrypted string
decryptSet to 1 when decrypting, or to 0 when encrypting

Definition at line 23 of file idcrypt.c.

32 {
33 char *keystr;
34 unsigned int len, r;
35
36 len=strlen(string);
37 if(len==0) return 0;
38
39 keystr = malloc(len);
40 if(!keystr) return 1;
41
42 if(len>strlen(key)) {
43 for(r=0;r<len;r++) {
44 keystr[r]=key[r%strlen(key)]-32;
45 if(keystr[r]>94) keystr[r]=94;
46 }
47 } else {
48 for(r=0;r<len;r++) {
49 keystr[r]=key[r]-32;
50 if(keystr[r]>94) keystr[r]=94;
51 }
52 }
53
54 for(r=0;r<len;r++) {
55 int c=(unsigned char)string[r]-32;
56 if(c>94) c=94;
57 if(decrypt) {
58 c=c-keystr[r];
59 if(c<0) c=(95-(-c)%95);
60 } else {
61 c=(c+keystr[r])%95;
62 }
63 out[r]=c+32;
64 }
65 out[r]=0;
66 free(keystr);
67 return 0;
68}

◆ iftDeleteItem()

int iftDeleteItem ( IFT * ift,
int item,
int verbose )
extern

Remove the specified item from IFT.

Returns
0 if ok.
See also
iftPut, iftEmpty, iftReplaceNthValue
Parameters
iftPointer to IFT structure.
itemIndex [0..keyNr-1] of key and value to delete.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 169 of file ift.c.

176 {
177 int i;
178
179 if(verbose>0) printf("%s(*ift, %d)\n", __func__, item);
180 if(ift==NULL) return(1);
181 iftSetStatus(ift, IFT_FAULT);
182 if(ift==NULL) {return(1);}
183 if(item<0 || item>=ift->keyNr) {return(2);}
184
185 if(ift->item[item].key!=NULL) free(ift->item[item].key);
186 if(ift->item[item].value!=NULL) free(ift->item[item].value);
187 ift->item[item].key=ift->item[item].value=NULL;
188 for(i=item+1; i<ift->keyNr; i++) {
189 ift->item[i-1].type=ift->item[i].type;
190 ift->item[i-1].sw=ift->item[i].sw;
191 ift->item[i-1].key=ift->item[i].key;
192 ift->item[i-1].value=ift->item[i].value;
193 ift->item[i].key=ift->item[i].value=NULL;
194 }
195 ift->keyNr--;
196 iftSetStatus(ift, IFT_OK);
197 return(0);
198}
IFT_KEY_AND_VALUE * item
Definition libtpcmisc.h:279

Referenced by ecat7CopyHeadersNoQuant().

◆ iftdup()

int iftdup ( IFT * ift1,
IFT * ift2,
int verbose )
extern

Make a copy (duplicate) of IFT structure.

Returns
Returns 0 (IFT_OK) when successful, otherwise an appropriate ift status code.
See also
iftInit, iftRead, iftPut, iftEmpty
Parameters
ift1Pointer to IFT structure to be copied.
ift2Pointer to initiated IFT structure; any previous contents are deleted.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 235 of file ift.c.

242 {
243 int ret, li;
244
245 if(verbose>0) printf("%s(*ift1, *ift2)\n", __func__);
246 /* Check the input */
247 if(ift1==NULL || ift2==NULL) return IFT_FAULT;
248
249 /* Empty the new IFT */
250 iftEmpty(ift2);
251
252 /* Copy the contents */
253 ift2->type=ift1->type;
254 ift2->status=ift1->status;
255 for(li=0; li<ift1->keyNr; li++) {
256 ret=iftPut(ift2, ift1->item[li].key, ift1->item[li].value, NULL, verbose);
257 if(ret!=IFT_OK) {iftEmpty(ift2); return(ret);}
258 ift2->item[li].type=ift1->item[li].type;
259 ift2->item[li].sw=ift1->item[li].sw;
260 }
261 // keyNr was set by iftPut()
262 return IFT_OK;
263}
const char * status
Definition libtpcmisc.h:277

Referenced by imgCopyhdr().

◆ iftEmpty()

void iftEmpty ( IFT * ift)
extern

Free memory allocated for IFT. All contents are destroyed.

See also
iftInit
Parameters
iftPointer to target IFT structure.

Definition at line 60 of file ift.c.

63 {
64 if(ift==NULL) return;
65 for(int i=0; i<ift->_memNr; i++) {
66 if(ift->item[i].key!=NULL) free(ift->item[i].key);
67 if(ift->item[i].value!=NULL) free(ift->item[i].value);
68 }
69 free(ift->item); ift->item=NULL; ift->_memNr=ift->keyNr=0;
70 ift->data=NULL; ift->datasize=0;
71}
unsigned char * data
Definition libtpcmisc.h:283
size_t datasize
Definition libtpcmisc.h:281

Referenced by cptReadOne(), defRead(), dftRead(), ehdrEmpty(), ematEmpty(), hrrtMakeCalHdr(), iftdup(), iftRead(), iftReadValue(), imgEmpty(), imgReadMicropetFrame(), imgReadMicropetHeader(), interfileIsHeader(), irdRead(), niftiHeaderToIFT(), readEcat931Calibrationfile(), res2ift(), tsvRead(), vrdRead(), and xelRead().

◆ iftFindNthKey()

int iftFindNthKey ( IFT * ift,
char * str,
int n,
int verbose )
extern

Find the Nth item of IFT where the specified string is found in the key. Comparison is case sensitive.

Returns
-1 if key was not found, or other negative value in case of an error, and the index [0..keyNr-1] if matching key is found.
See also
iftFindNthValue, iftGetNth, iftGet, iftGetFrom, iftGetKeyNr, iftRead, iftReplaceNthValue
Parameters
iftPointer to IFT structure.
strPointer to the case-sensitive (partial) key string.
nNth (1..keyNr-1) incidence of value is searched.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 84 of file iftsrch.c.

93 {
94 int li, found_nr=0;
95
96 if(verbose>0) printf("%s(*ift, \"%s\", %d)\n", __func__, str, n);
97 if(ift==NULL) {return(-10);}
98 if(str==NULL || strlen(str)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
99 if(n<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
100
101 /* Search the list */
102 for(li=0; li<ift->keyNr; li++) {
103 if(strstr(ift->item[li].key, str)!=NULL) {
104 found_nr++;
105 if(n==found_nr) {iftSetStatus(ift, IFT_OK); return(li);}
106 }
107 }
108 iftSetStatus(ift, IFT_KEYNOTFOUND);
109 return(-1);
110}

Referenced by cptReadOne().

◆ iftFindNthValue()

int iftFindNthValue ( IFT * ift,
char * str,
int n,
int verbose )
extern

Find the Nth item of IFT where the specified string is found in the value. Comparison is case sensitive.

Returns
-1 if key was not found, or other negative value in case of an error, and the index [0..keyNr-1] if matching value is found.
See also
iftFindNthKey, iftGetFrom, iftGetKeyNr, iftRead, iftReplaceNthValue
Parameters
iftPointer to IFT structure.
strPointer to the case-sensitive (partial) value string.
nNth (1..keyNr-1) incidence of value is searched..
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 120 of file iftsrch.c.

129 {
130 int li, found_nr=0;
131
132 if(verbose>0) printf("%s(*ift, \"%s\", %d)\n", __func__, str, n);
133 if(ift==NULL) {return(-10);}
134 if(str==NULL || strlen(str)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
135 if(n<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
136
137 /* Search the list */
138 for(li=0; li<ift->keyNr; li++) {
139 if(strstr(ift->item[li].value, str)!=NULL) {
140 found_nr++;
141 if(n==found_nr) {iftSetStatus(ift, IFT_OK); return(li);}
142 }
143 }
144 iftSetStatus(ift, IFT_VALUENOTFOUND);
145 return(-1);
146}

Referenced by cptReadOne(), and xelRead().

◆ iftGet()

int iftGet ( IFT * ift,
char * key,
int verbose )
extern

Find the key in the IFT and return the index [0..keyNr-1]. Key is case insensitive.

See also
iftGetNth, iftFindNthKey, iftGetFrom, iftGetKeyNr, iftRead, iftReplaceNthValue
Returns
-1 if key was not found, or other negative value in case of an error
Parameters
iftPointer to IFT structure.
keyPointer to the key string; contents are replaced by the correct key string.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 15 of file iftsrch.c.

22 {
23 int li;
24
25 if(verbose>0) printf("%s(*ift, \"%s\")\n", __func__, key);
26 if(ift==NULL) {return(-10);}
27 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
28
29 /* Search the list */
30 for(li=0; li<ift->keyNr; li++) {
31 if(strcasecmp(ift->item[li].key, key)==0) {
32 strcpy(key, ift->item[li].key);
33 iftSetStatus(ift, IFT_OK); return(li);
34 }
35 }
36 iftSetStatus(ift, IFT_KEYNOTFOUND);
37 return(-1);
38}

Referenced by cptReadOne(), dft_fill_hdr_from_IFT(), ecat7CopyHeadersNoQuant(), imgGetMicropetHeader(), irdRead(), niftiHeaderFromIFT(), tsvRead(), vrdRead(), and xelRead().

◆ iftGetDoubleValue()

int iftGetDoubleValue ( IFT * ift,
int si,
const char * key,
double * value,
int verbose )
extern

Finds the specified key string from IFT structure, and reads the corresponding value as double.

Returns
Returns the index of key/value, -1 if key or value was not found, and <-1 in case of an error.
See also
iftGetFloatValue, iftGetIntValue, iftRead
Parameters
iftPointer to existing IFT.
siIndex [0..keyNr-1] from which the search is started.
keyPointer to the key string; search is case-insensitive.
valuePointer to double variable where value is written; NaN is written in case of an error.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 268 of file iftsrch.c.

279 {
280 int li;
281
282 if(verbose>0) printf("%s(*ift, \"%s\", *value)\n", __func__, key);
283 if(ift==NULL) {return(-10);}
284 if(value==NULL) {iftSetStatus(ift, IFT_FAULT); return(-10);}
285 *value=nan("");
286 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
287 if(si<0) {iftSetStatus(ift, IFT_FAULT); return(-12);}
288 iftSetStatus(ift, IFT_VALUENOTFOUND);
289 /* Search the list */
290 for(li=si; li<ift->keyNr; li++) {
291 if(strcasecmp(ift->item[li].key, key)==0) {
292 if(ift->item[li].value==NULL || strlen(ift->item[li].value)<1) return -1;
293 (void)sscanf(ift->item[li].value, "%lf", value);
294 if(isnan(*value)) return -1;
295 iftSetStatus(ift, IFT_OK); return(li);
296 }
297 }
298 iftSetStatus(ift, IFT_KEYNOTFOUND);
299 return(-1);
300}

Referenced by hrrtMakeCalHdr().

◆ iftGetFloatValue()

int iftGetFloatValue ( IFT * ift,
int si,
const char * key,
float * value,
int verbose )
extern

Finds the specified key string from IFT structure, and reads the corresponding value as float.

See also
iftGetDoubleValue, iftGetIntValue
Returns
Returns the index of key/value, -1 if key or value was not found, and <-1 in case of an error.
Parameters
iftPointer to existing IFT.
siIndex [0..keyNr-1] from which the search is started.
keyPointer to the key string; search is case-insensitive.
valuePointer to float variable where value is written; NaN is written in case of an error.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 228 of file iftsrch.c.

239 {
240 int li;
241
242 if(verbose>0) printf("%s(*ift, \"%s\", *value)\n", __func__, key);
243 if(ift==NULL) {return(-10);}
244 if(value==NULL) {iftSetStatus(ift, IFT_FAULT); return(-10);}
245 *value=nanf("");
246 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
247 if(si<0) {iftSetStatus(ift, IFT_FAULT); return(-12);}
248 iftSetStatus(ift, IFT_VALUENOTFOUND);
249 /* Search the list */
250 for(li=si; li<ift->keyNr; li++) {
251 if(strcasecmp(ift->item[li].key, key)==0) {
252 if(ift->item[li].value==NULL || strlen(ift->item[li].value)<1) return -1;
253 (void)sscanf(ift->item[li].value, "%f", value);
254 if(isnan(*value)) return -1;
255 iftSetStatus(ift, IFT_OK); return(li);
256 }
257 }
258 iftSetStatus(ift, IFT_KEYNOTFOUND);
259 return(-1);
260}

Referenced by imgGetMicropetHeader(), imgReadMicropetFrame(), niftiHeaderFromIFT(), and upetReadImagedata().

◆ iftGetFrom()

int iftGetFrom ( IFT * ift,
int si,
const char * key,
int verbose )
extern

Finds the specified key in the IFT, starting from specified index. Key is case insensitive.

Returns
Returns the index of key/value, -1 if key or value was not found, and <-1 in case of an error.
See also
iftGetFullmatchFrom, iftFindNthValue
Parameters
iftPointer to existing IFT.
siIndex [0..keyNr-1] from which the search is started.
keyPointer to the key string; search is case-insensitive.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 156 of file iftsrch.c.

165 {
166 int li;
167
168 if(verbose>0) printf("%s(*ift, %d, \"%s\")\n", __func__, si, key);
169 if(ift==NULL) {return(-10);}
170 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
171 if(si<0) {iftSetStatus(ift, IFT_FAULT); return(-12);}
172
173 /* Search the list */
174 for(li=si; li<ift->keyNr; li++) {
175 if(strcasecmp(ift->item[li].key, key)==0) {
176 iftSetStatus(ift, IFT_OK); return(li);
177 }
178 }
179 iftSetStatus(ift, IFT_KEYNOTFOUND);
180 return(-1);
181}

Referenced by hrrtMakeCalHdr(), and interfileIsHeader().

◆ iftGetFullmatchFrom()

int iftGetFullmatchFrom ( IFT * ift,
int si,
const char * key,
const char * value,
int verbose )
extern

Finds the index with specified key and value in the IFT, starting from specified index. Key and value are case insensitive.

Returns
Returns the index of key/value, -1 if key or value was not found, and <-1 in case of an error.
See also
iftGetFrom, iftFindNthValue
Parameters
iftPointer to existing IFT.
siIndex [0..keyNr-1] from which the search is started.
keyPointer to the key string; search is case-insensitive.
valuePointer to the value string; search is case-insensitive.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 191 of file iftsrch.c.

202 {
203 int li;
204
205 if(verbose>0) printf("%s(*ift, %d, \"%s\", \"%s\")\n", __func__, si, key, value);
206 if(ift==NULL) {return(-10);}
207 if(key==NULL) {iftSetStatus(ift, IFT_FAULT); return(-11);}
208 if(value==NULL) {iftSetStatus(ift, IFT_FAULT); return(-12);}
209 if(si<0) {iftSetStatus(ift, IFT_FAULT); return(-13);}
210
211 /* Search the list */
212 for(li=si; li<ift->keyNr; li++) {
213 if(strcasecmp(ift->item[li].key, key)!=0) continue;
214 if(strcasecmp(ift->item[li].value, value)!=0) continue;
215 iftSetStatus(ift, IFT_OK); return(li);
216 }
217 iftSetStatus(ift, IFT_KEYNOTFOUND);
218 return(-1);
219}

Referenced by imgReadMicropetFrame(), and upetReadImagedata().

◆ iftGetIntValue()

int iftGetIntValue ( IFT * ift,
int si,
const char * key,
int * value,
int verbose )
extern

Finds the specified key string from IFT structure, and reads the corresponding value as int.

Returns
Returns the index of key/value, -1 if key or value was not found, and <-1 in case of an error.
See also
iftGetKeyNr, iftGetDoubleValue
Parameters
iftPointer to existing IFT.
siIndex [0..keyNr-1] from which the search is started.
keyPointer to the key string; search is case-insensitive.
valuePointer to int variable where value is written; -9999 is written in case of an error.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 309 of file iftsrch.c.

320 {
321 int li;
322
323 if(verbose>0) printf("%s(*ift, \"%s\", *value)\n", __func__, key);
324 if(ift==NULL) {return(-10);}
325 if(value==NULL) {iftSetStatus(ift, IFT_FAULT); return(-10);}
326 *value=-9999;
327 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
328 if(si<0) {iftSetStatus(ift, IFT_FAULT); return(-12);}
329 /* Search the list */
330 iftSetStatus(ift, IFT_VALUENOTFOUND);
331 for(li=si; li<ift->keyNr; li++) {
332 if(strcasecmp(ift->item[li].key, key)==0) {
333 if(ift->item[li].value==NULL || strlen(ift->item[li].value)<1) return -1;
334 (void)sscanf(ift->item[li].value, "%d", value);
335 if(*value==-9999) return -1;
336 iftSetStatus(ift, IFT_OK); return(li);
337 }
338 }
339 iftSetStatus(ift, IFT_KEYNOTFOUND);
340 return(-1);
341}

Referenced by hrrtMakeCalHdr(), imgGetMicropetHeader(), niftiHeaderFromIFT(), and upetReadImagedata().

◆ iftGetKeyNr()

int iftGetKeyNr ( IFT * ift,
const char * key,
int verbose )
extern

Find the nr of occurrences of the specified key in the IFT. Key is case insensitive.

See also
iftFindNthValue
Returns
Returns the nr of occurrences of the key.
Parameters
iftPointer to existing IFT
keyPointer to the key string
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 350 of file iftsrch.c.

357 {
358 int li, found_nr=0;
359
360 if(verbose>0) printf("%s(*ift, \"%s\")\n", __func__, key);
361 if(ift==NULL) {return(0);}
362 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(0);}
363 iftSetStatus(ift, IFT_KEYNOTFOUND);
364
365 /* Search the list */
366 for(li=0; li<ift->keyNr; li++) if(strcasecmp(ift->item[li].key, key)==0) found_nr++;
367 if(found_nr>0) iftSetStatus(ift, IFT_OK);
368 else iftSetStatus(ift, IFT_KEYNOTFOUND);
369 return(found_nr);
370}

◆ iftGetNth()

int iftGetNth ( IFT * ift,
char * key,
int n,
int verbose )
extern

Find the Nth key with similar name in the IFT and return the index [0..keyNr-1]. Key is case insensitive.

See also
iftFindNthKey, iftGet, iftGetFrom, iftGetKeyNr, iftRead, iftReplaceNthValue
Returns
-1 if key was not found, or other negative value in case of an error
Parameters
iftpointer to IFT structure.
keyPointer to the key string; contents are replaced by the correct key string.
nNth (1..) incidence of key is searched.
verboseVerbose level; if zero, then only warnings are printed into stderr.

Definition at line 48 of file iftsrch.c.

57 {
58 int li, found_nr=0;
59
60 if(verbose>0) printf("%s(*ift, \"%s\", %d)\n", __func__, key, n);
61 if(ift==NULL) {return(-10);}
62 if(key==NULL || strlen(key)<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
63 if(n<1) {iftSetStatus(ift, IFT_FAULT); return(-11);}
64
65 /* Search the list */
66 for(li=0; li<ift->keyNr; li++) {
67 if(strcasecmp(ift->item[li].key, key)==0) {
68 strcpy(key, ift->item[li].key); found_nr++;
69 if(n==found_nr) {iftSetStatus(ift, IFT_OK); return(li);}
70 }
71 }
72 iftSetStatus(ift, IFT_KEYNOTFOUND);
73 return(-1);
74}

Referenced by dft_fill_hdr_from_IFT(), and tsvRead().

◆ iftInit()

void iftInit ( IFT * ift)
extern

Initiate IFT structure. This should be called once before first use.

See also
iftEmpty, iftRead, iftPut
Parameters
iftPointer to target IFT structure.

Definition at line 45 of file ift.c.

48 {
49 if(ift==NULL) return;
50 memset(ift, 0, sizeof(IFT));
51 ift->_memNr=ift->keyNr=0; ift->item=NULL;
52 ift->data=NULL; ift->datasize=0;
53}

Referenced by cptReadOne(), dftRead(), ehdrInitiate(), ematInitiate(), hrrtMakeCalHdr(), iftReadValue(), imgInit(), interfileIsHeader(), irdRead(), readEcat931Calibrationfile(), tsvRead(), vrdRead(), and xelRead().

◆ iftPut()

int iftPut ( IFT * ift,
char * key,
char * value,
char * cmt_type,
int verbose )
extern

Add specified key and its value to the IFT.

Also comment type (first character pointed to) can be added. Either key or value can be empty, but not both of them.

Returns
Returns 0 if ok. Sets ift->status.
See also
iftInit, iftEmpty, iftPutDouble, iftDeleteItem
Parameters
iftPointer to initiated IFT; previous contents are not changed
keyKey string; can be empty ("" or NULL)
valueValue string; can be empty ("" or NULL)
cmt_typePointer to comment character, e.g. '#' or ';' or '!'; can be empty ("" or NULL)
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 82 of file ift.c.

93 {
94 int i, add_nr=1000;
95
96 if(ift==NULL) {return(1);}
97 if((key==NULL || strlen(key)<1) && (value==NULL || strlen(value)<1)) {
98 iftSetStatus(ift, IFT_FAULT); return(2);}
99 if(verbose>0) {
100 printf("%s(ift, ", __func__);
101 if(key!=NULL) printf("\"%s\", ", key); else printf("NULL, ");
102 if(value!=NULL) printf("\"%s\", ", value); else printf("NULL, ");
103 if(cmt_type!=NULL) printf("\"%1.1s\")\n", cmt_type); else printf("NULL)\n");
104 }
105
106 /* If necessary, allocate more memory for items */
107 if(ift->_memNr<=ift->keyNr) {
108 ift->item=realloc(ift->item, (ift->_memNr+add_nr)*sizeof(IFT_KEY_AND_VALUE));
109 if(ift->item==NULL) {iftSetStatus(ift, IFT_NOMEMORY); return(5);}
110 ift->_memNr+=add_nr;
111 for(i=ift->keyNr; i<ift->_memNr; i++) {
112 ift->item[i].type=(char)0;
113 ift->item[i].sw=(short int)0;
114 ift->item[i].key=NULL;
115 ift->item[i].value=NULL;
116 }
117 }
118
119 /* Set the contents */
120 /* type */
121 if(cmt_type!=NULL) ift->item[ift->keyNr].type=cmt_type[0];
122 /* key */
123 if(key!=NULL) ift->item[ift->keyNr].key=strdup(key);
124 else ift->item[ift->keyNr].key=strdup("");
125 if(ift->item[ift->keyNr].key==NULL) {iftSetStatus(ift, IFT_NOMEMORY); return(7);}
126 /* value */
127 if(value!=NULL) ift->item[ift->keyNr].value=strdup(value);
128 else ift->item[ift->keyNr].value=strdup("");
129 if(ift->item[ift->keyNr].value==NULL) {iftSetStatus(ift, IFT_NOMEMORY); return(8);}
130
131 ift->keyNr++;
132 iftSetStatus(ift, IFT_OK);
133 return(0);
134}

Referenced by defRead(), ecat7ImageheaderToIFT(), ecat7MHeaderToIFT(), ecat7ScanheaderToIFT(), hrrtMakeCalHdr(), iftdup(), iftPutDouble(), iftRead(), niftiHeaderToIFT(), and res2ift().

◆ iftPutDouble()

int iftPutDouble ( IFT * ift,
char * key,
double value,
char * cmt_type,
int verbose )
extern

Add specified key and its floating point (double) value to the IFT.

Also comment type (first character pointed to) can be added. Key can be empty.

Returns
Returns 0 if ok. Sets ift->status.
See also
iftPut
Parameters
iftPointer to initiated IFT; previous contents are not changed
keyKey string; can be empty ("" or NULL)
valueValue as double
cmt_typePointer to comment character, e.g. '#' or ';' or '!'; can be empty ("" or NULL)
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 145 of file ift.c.

157 {
158 char dstr[128];
159 sprintf(dstr, "%g", value);
160 return(iftPut(ift, key, dstr, cmt_type, verbose));
161}

Referenced by hrrtMakeCalHdr().

◆ iftRead()

int iftRead ( IFT * ift,
char * filename,
int is_key_required,
int verbose )
extern

Read IFT file keys and values. Previous contents of IFT are preserved.

This function can read the initial ASCII part of files that contain also binary data.

Returns
Returns 0 if ok. Sets ift->status.
See also
iftdup, iftInit, iftEmpty, defRead
Parameters
iftPointer to initiated but empty IFT structure.
filenameInput file name.
is_key_required0=key name is not required, 1=only lines with key and equals sign are read.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 24 of file iftfile.c.

33 {
34 int i, ret, nr=0, line=0, eq_type=0, initial_key_nr=0, nonprintable=0;
35 char *allfile, *cptr, *key_ptr, *value_ptr, *eq_ptr, *eq_ptr2, *cmt_ptr;
36 char empty_char=(char)0;
37 FILE *fp;
38
39
40 /* Check function input */
41 if(verbose>0) printf("%s(*ift, %s)\n", __func__, filename);
42 if(ift==NULL) return(1);
43 if(filename==NULL || strlen(filename)<1) {
44 iftSetStatus(ift, IFT_FAULT); return(1);
45 }
46 if(ift->keyNr>0) initial_key_nr=ift->keyNr;
47
48 /* Open file */
49 if(strcasecmp(filename, "stdin")==0) {
50 fp=stdin;
51 } else {
52 fp=fopen(filename, "r");
53 if(fp==NULL) {iftSetStatus(ift, IFT_CANNOTREAD); return(2);}
54 }
55
56 /* Get file size */
57 nr=nonprintable=0; while((ret=fgetc(fp))!=EOF) {
58 if(iscntrl(ret) && ret!=13 && ret!=10 && ret!=9) {
59 nonprintable=1; break;}
60 nr++;
61 }
62 if(nr<2) {
63 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
64 if(nonprintable>0) {
65 /* File contains non-printable characters; maybe binary file */
66 iftSetStatus(ift, IFT_UNKNOWNFORMAT);
67 } else {
68 /* File just din't have any content */
69 iftSetStatus(ift, IFT_NODATA);
70 }
71 return(3);
72 }
73 if(verbose>1) printf(" the size of file is %d bytes\n", nr);
74 if(nr>5000000) {
75 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
76 iftSetStatus(ift, IFT_UNKNOWNFORMAT); return(3);
77 }
78 rewind(fp);
79
80 /* Allocate memory for file contents; calloc and extra space to end with 0. */
81 allfile=(char*)calloc((nr+3), sizeof(char));
82 if(allfile==NULL) {
83 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
84 iftSetStatus(ift, IFT_NOMEMORY); return(4);
85 }
86
87 /* Read file contents and close the file */
88 i=0; while((ret=fgetc(fp))!=EOF && i<nr) allfile[i++]=(char)ret;
89 if(strcasecmp(filename, "stdin")!=0) fclose(fp);
90 /* Make sure that file ends with CR or LF */
91 if(allfile[i-1]!=10 && allfile[i-1]!=13) {allfile[i++]=(char)13; allfile[i++]=(char)10;}
92
93 /* and then fill the list */
94 /* separate the first line */
95 cptr=strtok(allfile, "\n\r"); line=0;
96 do {
97 if(verbose>2) printf("line %d: '%s'\n", line, cptr);
98 /* Remove initial spaces and tabs */
99 i=strspn(cptr, " \t"); cptr+=i;
100 if(strlen(cptr)<1) {cptr=strtok(NULL, "\n\r"); line++; continue;}
101 /* Check if line starts with a comment character */
102 if((cmt_ptr=strchr("#!;%", cptr[0]))!=NULL) {
103 cmt_ptr=cptr; cptr++; i=strspn(cptr, " \t"); cptr+=i;
104 if(strlen(cptr)<1) {cptr=strtok(NULL, "\n\r"); line++; continue;}
105 }
106 if(verbose>2) printf(" line %d: '%s'\n", line, cptr);
107 /* Find the 'equals' sign */
108 eq_ptr=strstr_noquotation(cptr, ":=");
109 if(eq_ptr==NULL) eq_ptr=strstr_noquotation(cptr, "=");
110 if(eq_ptr==NULL) {
111 eq_ptr=strstr_noquotation(cptr, ":");
112 /* do not accept time representation */
113 if(eq_ptr!=NULL && strlen(cptr)>=strlen(eq_ptr)+2 && istime(eq_ptr-2)<=0) {
114 /* ... but search for later equals sign */
115 eq_ptr2=strstr_noquotation(eq_ptr+4, ":"); eq_ptr=NULL;
116 if(eq_ptr2!=NULL && strlen(cptr)>=strlen(eq_ptr2)+2) {
117 if(istime(eq_ptr2-2)<=0) eq_ptr2=NULL; else eq_ptr=eq_ptr2;
118 }
119 }
120 }
121 if(eq_ptr==NULL) {
122 /* Equals sign not found; if required, then ignore this line */
123 if(is_key_required) {cptr=strtok(NULL, "\n\r"); line++; continue;}
124 /* If not required, then key="" */
125 key_ptr=eq_ptr=&empty_char; value_ptr=cptr;
126 } else {
127 if(strncmp(eq_ptr, ":=", 2)==0) eq_type=1;
128 else if(strncmp(eq_ptr, "=", 1)==0) eq_type=2;
129 else if(strncmp(eq_ptr, ":", 1)==0) eq_type=3;
130 else eq_type=0;
131 *eq_ptr=(char)0; eq_ptr++; key_ptr=cptr;
132 /* Find the end of the 'equals' sign; that is the start of value */
133 i=strspn(eq_ptr, ":="); value_ptr=eq_ptr+i;
134 /* Remove initial spaces and tabs */
135 i=strspn(value_ptr, " \t"); value_ptr+=i;
136 }
137 /* Remove tail spaces and tabs */
138 i=strlen(key_ptr); while(i>0 && isspace((int)key_ptr[i-1])) i--; key_ptr[i]=(char)0;
139 if(i==0) { /* Length of key name is zero */
140 if(is_key_required) {cptr=strtok(NULL, "\n\r"); line++; continue;}
141 }
142 i=strlen(value_ptr); while(i>0 && isspace((int)value_ptr[i-1])) i--; value_ptr[i]=(char)0;
143 if(verbose>2) printf(" key='%s' value='%s'\n", key_ptr, value_ptr);
144 /* Remove quotation marks */
145 i=strlen(key_ptr)-1; if(i<0) i=0;
146 if((key_ptr[0]=='\'' && key_ptr[i]=='\'') || (key_ptr[0]=='\"' && key_ptr[i]=='\"')) {
147 key_ptr[i]=(char)0; if(i>0) key_ptr++;}
148 if(strlen(key_ptr)<1) { /* Length of key name without comments is zero */
149 if(is_key_required) {cptr=strtok(NULL, "\n\r"); line++; continue;}
150 }
151 i=strlen(value_ptr)-1; if(i<0) i=0;
152 if((value_ptr[0]=='\'' && value_ptr[i]=='\'') || (value_ptr[0]=='\"' && value_ptr[i]=='\"')) {
153 value_ptr[i]=(char)0; if(i>0) value_ptr++;}
154 if(verbose>2) printf(" key='%s' value='%s'\n", key_ptr, value_ptr);
155 /* Put key and value in the list */
156 ret=iftPut(ift, key_ptr, value_ptr, cmt_ptr, verbose-1);
157 if(ret) {
158 free(allfile); iftEmpty(ift); iftSetStatus(ift, IFT_FAULT);
159 return(10+ret);
160 }
161 /* separate the next line */
162 cptr=strtok(NULL, "\n\r"); line++;
163 } while(cptr!=NULL);
164 free(allfile);
165 if(verbose>2) printf("eq_type=%d\n", eq_type);
166 ift->type=eq_type;
167 /* Did we actually get any data? */
168 if(ift->keyNr<=initial_key_nr) {iftSetStatus(ift, IFT_NODATA); return(7);}
169
170 iftSetStatus(ift, IFT_OK);
171 return(0);
172}
int istime(char *str)
Definition datetime.c:259
char * strstr_noquotation(const char *str1, const char *str2)
Definition quots.c:17

Referenced by cptReadOne(), dftRead(), hrrtMakeCalHdr(), iftReadValue(), interfileIsHeader(), irdRead(), readEcat931Calibrationfile(), tsvRead(), vrdRead(), and xelRead().

◆ iftReadValue()

char * iftReadValue ( char * filename,
char * keystr,
int verbose )
extern

Read value string from IFT file.

Returns
Returns pointer to a locally allocated copy of the value string, or NULL if none found; free the returned pointer when no more needed.
Parameters
filenameFile name.
keystrString to search for in the key. If NULL, or key containing the string is not found, then if there is only one value in the file, pointer to that is returned.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 180 of file iftfile.c.

188 {
189 if(filename==NULL || !filename[0]) return(NULL);
190 /* Read the file */
191 IFT ift; iftInit(&ift); if(iftRead(&ift, filename, 0, verbose)!=0) return(NULL);
192 /* If file contains just one value, then return pointer to a copy of that */
193 if(ift.keyNr==1 && strlen(ift.item[0].value)>0) {
194 char *s=strdup(ift.item[0].value);
195 iftEmpty(&ift);
196 return(s);
197 }
198 /* If key string to search for was not given, then we cannot do more */
199 if(keystr==NULL || strlen(keystr)<1) return(NULL);
200 /* Search the list for the key */
201 int i=-1;
202 for(int li=0; li<ift.keyNr; li++) {
203 if(strcasestr(ift.item[li].key, keystr)!=NULL && strlen(ift.item[li].value)>0) {
204 i=li; break;
205 }
206 }
207 if(i<0) return(NULL);
208 /* If found, then return pointer to a copy of that */
209 char *s=strdup(ift.item[i].value);
210 iftEmpty(&ift);
211 return(s);
212}
void iftInit(IFT *ift)
Definition ift.c:45
int iftRead(IFT *ift, char *filename, int is_key_required, int verbose)
Definition iftfile.c:24

◆ iftReplaceNthValue()

int iftReplaceNthValue ( IFT * ift,
int item,
char * value,
int verbose )
extern

Replaces specified value in IFT with a new value.

Returns
0 if ok.
See also
iftDeleteItem, iftPut
Parameters
iftPointer to IFT structure.
itemIndex [0..keyNr-1] of key and value.
valueValue string; can be empty ("" or NULL).
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 206 of file ift.c.

215 {
216 if(ift==NULL) {return(1);}
217 if(item>=ift->keyNr) {iftSetStatus(ift, IFT_FAULT); return(2);}
218 if(verbose>0) printf("%s(ift, %d, %s)\n", __func__, item, value);
219 /* Delete old value */
220 if(ift->item[item].value!=NULL) free(ift->item[item].value);
221 /* Set new value */
222 if(value!=NULL) ift->item[item].value=strdup(value);
223 else ift->item[item].value=strdup("");
224 if(ift->item[item].value==NULL) {iftSetStatus(ift, IFT_NOMEMORY); return(8);}
225 iftSetStatus(ift, IFT_OK);
226 return(0);
227}

◆ iftSetStatus()

void iftSetStatus ( IFT * ift,
int status )
extern

Sets IFT status

Parameters
iftPointer to target IFT structure.
statusNew status value.

Definition at line 29 of file ift.c.

34 {
35 if(ift==NULL) return;
36 if(status<0 || status>8) ift->status=ift_status[IFT_FAULT];
37 else ift->status=ift_status[status];
38}

Referenced by defRead(), iftDeleteItem(), iftFindNthKey(), iftFindNthValue(), iftGet(), iftGetDoubleValue(), iftGetFloatValue(), iftGetFrom(), iftGetFullmatchFrom(), iftGetIntValue(), iftGetKeyNr(), iftGetNth(), iftPut(), iftRead(), iftReplaceNthValue(), iftWrite(), and iftWriteItem().

◆ iftWrite()

int iftWrite ( IFT * ift,
char * filename,
int verbose )
extern

Write all keys and values.

Returns
0 if ok.
See also
iftInit, iftRead, iftWriteItem
Parameters
iftPointer to IFT structure.
filenameOutput filename, or string "stdout" to print on console.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 282 of file iftfile.c.

289 {
290 int li, ret;
291 FILE *fp;
292
293 if(verbose>0) printf("%s(*ift, %s)\n", __func__, filename);
294 if(ift==NULL) return(1);
295 if(filename==NULL || strlen(filename)<1) {iftSetStatus(ift, IFT_FAULT); return(1);}
296 if(ift->keyNr<1) return(0);
297
298 /* Open file */
299 if(strcasecmp(filename, "stdout")==0) {
300 fp=stdout;
301 } else {
302 fp=fopen(filename, "w");
303 if(fp==NULL) {iftSetStatus(ift, IFT_CANNOTWRITE); return(2);}
304 }
305
306 /* Write the contents */
307 for(li=0, ret=0; li<ift->keyNr; li++) {
308 ret=iftWriteItem(ift, li, fp, verbose);
309 if(ret) break;
310 }
311 if(strcasecmp(filename, "stdout")!=0) fclose(fp);
312 return(ret);
313}
int iftWriteItem(IFT *ift, int item, FILE *fp, int verbose)
Definition iftfile.c:221

Referenced by cptReadOne(), ecat7MainheaderFromIFT(), ecat7ReadHeaders(), hrrtMakeCalHdr(), and niftiHeaderFromIFT().

◆ iftWriteItem()

int iftWriteItem ( IFT * ift,
int item,
FILE * fp,
int verbose )
extern

Write one item in IFT to the specified file pointer.

See also
iftInit, iftEmpty, iftRead, iftWrite
Returns
0 if ok.
Parameters
iftPointer to initiated but empty IFT structure.
itemIndex [0..keyNr-1] of key and value to write.
fpOutput file pointer.
verboseVerbose level; if zero, then only warnings are printed into stderr

Definition at line 221 of file iftfile.c.

230 {
231 char eq_sign[3];
232 int ret;
233
234 if(verbose>0) printf("%s(*ift, %d, fp)\n", __func__, item);
235 if(ift==NULL) {return(1);}
236 iftSetStatus(ift, IFT_FAULT);
237 if(fp==NULL) {return(2);}
238 if(item<0 || item>=ift->keyNr) {return(3);}
239
240 iftSetStatus(ift, IFT_OK);
241 switch(ift->type) {
242 case 1: strcpy(eq_sign, ":="); break;
243 case 2: strcpy(eq_sign, "="); break;
244 case 3: strcpy(eq_sign, ":"); break;
245 case 4: strcpy(eq_sign, " "); break;
246 case 5: strcpy(eq_sign, "\t"); break;
247 case 6: strcpy(eq_sign, ","); break;
248 case 7: strcpy(eq_sign, ";"); break;
249 default: strcpy(eq_sign, ":="); break;
250 }
251 if(ift->item[item].type!=' ' && ift->item[item].type!=(char)0) {
252 ret=fprintf(fp, "%c ", ift->item[item].type);
253 if(ret<1) {iftSetStatus(ift, IFT_CANNOTWRITE); return(6);}
254 }
255 if(ift->item[item].key==NULL || strlen(ift->item[item].key)<1) {
256 ret=fprintf(fp, "%s\n", ift->item[item].value);
257 } else {
259 ift->type==4 || ift->type==5 || ift->type==6 || ift->type==7)
260 ret=fprintf(fp, "%s%s%s\n",
261 ift->item[item].key, eq_sign, ift->item[item].value);
263 ret=fprintf(fp, "%s %s%s\n",
264 ift->item[item].key, eq_sign, ift->item[item].value);
266 ret=fprintf(fp, "%s%s %s\n",
267 ift->item[item].key, eq_sign, ift->item[item].value);
268 else
269 ret=fprintf(fp, "%s %s %s\n",
270 ift->item[item].key, eq_sign, ift->item[item].value);
271 }
272 if(ret<1) {iftSetStatus(ift, IFT_CANNOTWRITE); return(6);}
273 return(0);
274}
int IFT_SPACE_BEFORE_EQ_SIGN
Definition iftfile.c:11
int IFT_SPACE_AFTER_EQ_SIGN
Definition iftfile.c:13

Referenced by iftWrite().

◆ integerListAdd()

int integerListAdd ( INTEGER_LIST * l,
int v,
int ifnew )
extern

Add one integer to INTEGER_LIST.

See also
integerListInit, integerListSort, integerListAddFromString, integerListExpandFromString.
Returns
Returns the number of added integers (0 or 1), or <0 in case of an error.
Parameters
lPointer to initiated list
vInteger value to add
ifnewAdd integer to the list only if it is new (0=no, 1=yes)

Definition at line 190 of file intex.c.

197 {
198 int i;
199 if(l==NULL) return(-1);
200
201 /* If only new value is to be added, then check that this is new */
202 if(ifnew!=0) {for(i=0; i<l->nr; i++) if(l->list[i]==v) return(0);}
203 /* Add value to list if there is space left, and quit */
204 if(l->_allocNr>l->nr) {l->list[l->nr++]=v; return(1);}
205 /* Allocate more space */
206 if(l->_allocNr==0) l->list=(int*)malloc(10*sizeof(int));
207 else l->list=(int*)realloc(l->list, (10+l->_allocNr)*sizeof(int));
208 if(l->list==NULL) {l->nr=l->_allocNr=0; return(-2);}
209 l->_allocNr+=10;
210 /* Add value to list */
211 l->list[l->nr++]=v;
212 return(1);
213}

Referenced by imgMaskRoiNr(), integerListAddFromString(), and integerListExpandFromString().

◆ integerListAddFromString()

int integerListAddFromString ( const char * s1,
const char * s2,
INTEGER_LIST * l,
const int ifnew )
extern

Read a list of integer values from given string with given delimiters.

See also
integerListInit, integerListSort, integerListAdd, integerListExpandFromString.
Returns
The number of added integer values, or <0 in case of an error.
Author
Vesa Oikonen
Parameters
s1Pointer to string from which the integers are read, for example "2,3,6,8".
s2String containing character delimiters, for example ", ".
lPointer to INTEGER_LIST struct; previous contents are preserved.
ifnewAdd integer to the list only if it is new (0=no, 1=yes)

Definition at line 242 of file intex.c.

252 {
253 if(l==NULL) return(-1);
254 if(s1==NULL || s2==NULL) return(0);
255
256 /* Get the nr of tokens */
257 int i, j, m, n, v;
258 n=strTokenNr((char*)s1, s2); if(n<1) return(0);
259 /* Read the values */
260 char tmp[128];
261 for(i=j=0; i<n; i++) {
262 if(strTokenNCpy(s1, s2, 1+i, tmp, 128)<1) return(-2);
263 if(atoi_with_check(tmp, &v)) return(-3);
264 m=integerListAdd(l, v, ifnew); if(m<0) return(-4);
265 j+=m;
266 }
267 return(j);
268}
int atoi_with_check(const char *int_as_string, int *result_value)
Definition decpoint.c:238
int integerListAdd(INTEGER_LIST *l, int v, int ifnew)
Definition intex.c:190
int strTokenNCpy(const char *str1, const char *str2, int i, char *str3, int count)
Definition strext.c:45
int strTokenNr(const char *str1, const char *str2)
Definition strext.c:17

◆ integerListEmpty()

int integerListEmpty ( INTEGER_LIST * l)
extern

Free the memory allocated in the INTEGER_LIST struct.

See also
integerListInit, integerListSort, integerListAdd.
Returns
Returns <>0 in case of an error.
Parameters
lPointer to INTEGER_LIST struct

Definition at line 175 of file intex.c.

178 {
179 if(l==NULL) return -1;
180 if(l->_allocNr>0) free(l->list);
181 l->nr=l->_allocNr=0;
182 l->list=NULL;
183 return 0;
184}

Referenced by imgMaskRoiNr().

◆ integerListExpandFromString()

int integerListExpandFromString ( const char * s1,
const char * s2,
INTEGER_LIST * l,
const int ifnew )
extern

Read ranges and individual integer values from given string with given delimiters.

See also
integerListInit, integerListSort, integerListAdd, integerListAddFromString.
Returns
The number of added integer values, or <0 in case of an error.
Author
Vesa Oikonen
Parameters
s1Pointer to string from which the integers are read, for example "0-8,12,32-28" or "0..8, 12, 28..34".
s2String containing character delimiters, for example ", ".
lPointer to INTEGER_LIST struct; previous contents are preserved.
ifnewAdd integer to the list only if it is new (0=no, 1=yes)

Definition at line 278 of file intex.c.

288 {
289 if(l==NULL) return(-1);
290 if(s1==NULL || s2==NULL) return(0);
291
292 /* Get the nr of tokens */
293 int n=strTokenNr((char*)s1, s2); if(n<1) return(0);
294 /* Read the values */
295 char tmp[128], tmp2[128], *t, *tail;
296 int i, j, m, first, last, sw;
297 for(i=j=0; i<n; i++) {
298 if(strTokenNCpy(s1, s2, 1+i, tmp, 128)<1) return(-2);
299 t=tmp; errno=0;
300 first=strtol(t, &tail, 10); if(errno) return(-3);
301 if(*tail) {
302 strcpy(tmp2, tail); t=tmp2;
303 if(*t=='-') t++;
304 else if(*t=='.') {t++; if(*t=='.') t++; else return(-4);}
305 else return(-5);
306 if(!*t) return(-6);
307 last=strtol(t, &tail, 10); if(errno) return(-7);
308 if(*tail) return(-8);
309 } else {
310 last=first;
311 }
312
313 if(first>last) {sw=first; first=last; last=sw;}
314 for(int v=first; v<=last; v++) {
315 m=integerListAdd(l, v, ifnew); if(m<0) return(-10);
316 j+=m;
317 }
318 }
319 return(j);
320}

◆ integerListInit()

int integerListInit ( INTEGER_LIST * l)
extern

Call this (once) before using INTEGER_LIST struct for the first time.

See also
integerListEmpty, integerListSort, integerListAddFromString, integerListExpandFromString.
Returns
Returns <>0 in case of an error.
Parameters
lPointer to INTEGER_LIST struct

Definition at line 161 of file intex.c.

164 {
165 if(l==NULL) return -1;
166 l->nr=l->_allocNr=0;
167 l->list=NULL;
168 return 0;
169}

◆ integerListSort()

int integerListSort ( INTEGER_LIST * l)
extern

Sort INTEGER_LIST

See also
integerListInit, integerListAdd, integerListAddFromString, integerListExpandFromString.
Returns
Returns <>0 in case of an error.
Parameters
lPointer to INTEGER_LIST struct

Definition at line 219 of file intex.c.

222 {
223 int i, j, v;
224
225 if(l==NULL) return -1;
226 if(l->nr<2) return 0;
227 for(i=0; i<l->nr; i++) for(j=i+1; j<l->nr; j++) {
228 if(l->list[i]>l->list[j]) {
229 v=l->list[i]; l->list[i]=l->list[j]; l->list[j]=v;
230 }
231 }
232 return 0;
233}

Referenced by imgMaskRoiNr().

◆ intEmpty()

void intEmpty ( INT_list * l)
extern

Free the memory allocated in the INT_LIST struct.

Parameters
lPointer to INT_LIST struct

Definition at line 23 of file intex.c.

26 {
27 if(l==NULL) return;
28 if(l->nr>0) free(l->i);
29 l->nr=0;
30 l->i=NULL;
31 return;
32}

Referenced by intExpand().

◆ intExpand()

int intExpand ( char * text,
INT_list * list )
extern

Existing list is freed and all data is cleared. Deprecated. Expanded integers are listed in list.i[] in increasing order.

Parameters
textInteger expressions to be expanded, e.g. 0-8,12,34-28
listPointer for int list data
Returns
0 if ok and at least one integer is listed.
See also
integerListAddFromString, integerListExpandFromString.

Definition at line 43 of file intex.c.

43 {
44 int j;
45 char *p, *t;
46 int first, last, swap, intMax=65536;
47
48 /* Check the arguments */
49 if(strlen(text)<1) return(1);
50 intEmpty(list);
51
52 /* Expand */
53 p=strtok(text, " ,;.&\t\n\r\0");
54 while(p!=NULL) {
55 t=p; first=last=-1;
56 while((*t!='-') && (!isdigit((int)*t)) && (*t)) t++;
57 if(*t=='-') {
58 while((!isdigit((int)*t)) && (*t)) t++;
59 if(isdigit((int)*t)) {first=0; last=atoi(t);}
60 } else if(isdigit((int)*t)) {
61 first=atoi(t); /*if (first==0) first=1;*/
62 while((isdigit((int)*t)) && (*t)) t++;
63 if(*t == '-') {
64 t++; while((!isdigit((int)*t)) && (*t)) t++;
65 if(isdigit((int)*t)) last=atoi(t); else last=intMax;
66 }
67 }
68 if((first>=0) && (last>=0)) {
69 if(first>last) {swap=first; first=last; last=swap;}
70 if(last>intMax) {if(first<=intMax) last=intMax; else last=0;}
71 for(j=first; j<=last && list->nr<intMax; j++)
72 if(_intexadd(list, j)<0) return(2);
73 } else if(first>=0) {
74 if(first<=intMax) if(_intexadd(list, first)<0) return(3);
75 } else if(last>=0) {
76 if(last>=intMax) if(_intexadd(list, last)<0) return(4);
77 }
78 p=strtok(NULL, " ,;.&\t\n\r\0");
79 }
80 if(list->nr<1) return(1);
81 return(0);
82}
void intEmpty(INT_list *l)
Definition intex.c:23
int _intexadd(INT_list *list, int a)
Definition intex.c:92
void swap(void *orig, void *new, int size)
Definition swap.c:31

◆ intInit()

void intInit ( INT_list * l)
extern

Call this (once) before using INT_LIST struct for the first time.

Parameters
lPointer to INT_LIST struct

Definition at line 12 of file intex.c.

15 {
16 if(l==NULL) return;
17 l->nr=0;
18 l->i=NULL;
19 return;
20}

◆ intMerge()

INT_list intMerge ( INT_list * list1,
INT_list * list2 )
extern

Merges two lists and returns the result. (the originals are not touched) Duplicate entries are removed. Deprecated.

Parameters
list1The first list
list2The second list
Returns
pointer to the new combined list.

Definition at line 124 of file intex.c.

124 {
125 int r,count=0,l1=0,l2=0;
126 INT_list newlist;
127 int *tmplist;
128 int found;
129 tmplist=(int*)malloc(sizeof(int)*(list1->nr+list2->nr));
130 while(l1<list1->nr || l2<list2->nr) {
131 if(l1<list1->nr) {
132 tmplist[count]=list1->i[l1];
133 count++;
134 l1++;
135 }
136 found=0;
137 if(l2<list2->nr) {
138 for(r=0;r<count;r++) {
139 if(tmplist[r]==list2->i[l2]) found++;
140 }
141 if(found<1) {
142 tmplist[count]=list2->i[l2]; count++;
143 }
144 l2++;
145 }
146 }
147 newlist.i=(int*)malloc(sizeof(int)*count);
148 memcpy(newlist.i,tmplist,count*sizeof(int));
149 newlist.nr=count;
150 free(tmplist);
151 return newlist;
152}

◆ inverfc()

double inverfc ( double x)
extern

Inverse complementary error function erfc^{-1}(x).

Based on the code by Acklam PJ, 2010.

Returns
Returns an approximate value of erfc^{-1}(x).
Parameters
xParameter for the inverse complementary error function.

Definition at line 205 of file doubleutil.c.

208 {
209 static const double a[] = {
210 -3.969683028665376E+01, 2.209460984245205E+02, -2.759285104469687E+02,
211 1.383577518672690E+02, -3.066479806614716E+01, 2.506628277459239
212 };
213 static const double b[] = {
214 -5.447609879822406E+01, 1.615858368580409E+02, -1.556989798598866E+02,
215 6.680131188771972E+01, -1.328068155288572E+01
216 };
217 static const double c[] = {
218 -7.784894002430293E-03, -3.223964580411365E-01, -2.400758277161838,
219 -2.549732539343734, 4.374664141464968, 2.938163982698783
220 };
221 static const double d[] = {
222 7.784695709041462E-03, 3.224671290700398E-01, 2.445134137142996, 3.754408661907416
223 };
224 double y, e, u;
225 x/=2.0;
226 if(x<0.02425) {
227 double q=sqrt(-2.0 * log(x));
228 y = (((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5])
229 / ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0);
230 } else if(x<=0.97575) {
231 double q=x-0.5;
232 double r=q*q;
233 y = (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q
234 / (((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1.0);
235 } else {
236 double q=sqrt(-2.0 * log(1.0-x));
237 y = -(((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5])
238 / ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0);
239 }
240 e=0.5*erfc(-y/M_SQRT2)-x;
241 u=(e)*M_SQRT2*M_PI*exp(0.5*y*y);
242 y-=u/(1.0 + 0.5*y*u);
243 return(fabs(y/M_SQRT2));
244}

Referenced by imgGaussianFIRFilter().

◆ isdate()

int isdate ( char * str)
extern

Check if specified string contains date in correct international format (YYYY-MM-DD). String must start with date, but any contents after it is ignored.

Returns
Returns 0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise <>0.
Parameters
strString to be checked; not changed in this routine

Definition at line 146 of file datetime.c.

149 {
150 int Y, M, D, n;
151 if(strlen(str)<10) return 1;
152 if(str[4]!='-' || str[7]!='-') return 2;
153 if(strncasecmp(str, "YYYY-MM-DD", 10)==0) return -1;
154 n=sscanf(str, "%4d-%2d-%2d", &Y, &M, &D); if(n!=3) return 3;
155 if(M>12 || D>31) return -1;
156 if(Y<0 || M<1 || D<1) return -1;
157 return 0;
158}

Referenced by dcmDA2intl(), get_date(), and isdatetime().

◆ isdate2()

int isdate2 ( char * str,
char * intdate )
extern

Check if specified string contains date in correct format (DD.MM.YYYY or DD/MM/YYYY). String must start with date, but any contents after it is ignored.

Returns
Returns 0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise <>0.
Parameters
strString to be checked; not changed in this routine
intdatePointer to allocated string where date is written in international format; enter NULL, if not needed.

Definition at line 168 of file datetime.c.

174 {
175 int Y, M, D, n;
176 if(strlen(str)<10) return 1;
177 if(str[2]!='.' && str[2]!='/') return 2;
178 if(str[5]!='.' && str[5]!='/') return 2;
179 if(isspace(str[8])) return 2;
180 if(strncasecmp(str, "DD.MM.YYYY", 10)==0 ||
181 strncasecmp(str, "DD/MM/YYYY", 10)==0) return -1;
182 n=sscanf(str, "%2d/%2d/%4d", &D, &M, &Y);
183 if(n<3) n=sscanf(str, "%2d.%2d.%4d", &D, &M, &Y);
184 if(n!=3) return 3;
185 if(M>12 || D>31) return -1;
186 if(Y<0 || M<1 || D<1) return -1;
187 if(intdate!=NULL) sprintf(intdate, "%04d-%02d-%02d", Y, M, D);
188 return 0;
189}

Referenced by get_date(), and isdatetime().

◆ isdate3()

int isdate3 ( char * str,
char * intdate )
extern

Check if specified string contains date in correct format (DD.MM.YY or DD/MM/YY). String must start with date, but any contents after it is ignored.

Returns
Returns 0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise <>0.
Parameters
strString to be checked; not changed in this routine
intdatePointer to allocated string where date is written in international format; enter NULL, if not needed.

Definition at line 199 of file datetime.c.

205 {
206 int Y, M, D, n;
207 if(strlen(str)<8) return 1;
208 if(str[2]!='.' && str[2]!='/') return 2;
209 if(str[5]!='.' && str[5]!='/') return 2;
210 if(strncasecmp(str, "DD.MM.YY", 8)==0 ||
211 strncasecmp(str, "DD/MM/YY", 8)==0) return -1;
212 n=sscanf(str, "%2d/%2d/%2d", &D, &M, &Y);
213 if(n<3) n=sscanf(str, "%2d.%2d.%2d", &D, &M, &Y);
214 if(n!=3) return 3;
215 if(Y>99 || M>12 || D>31) return -1;
216 if(Y<0 || M<1 || D<1) return -1;
217 if(intdate!=NULL) {
218 if(Y>=70) Y+=1900; else Y+=2000;
219 sprintf(intdate, "%04d-%02d-%02d", Y, M, D);
220 }
221 return 0;
222}

Referenced by get_date(), and isdatetime().

◆ isdate4()

int isdate4 ( int dateint,
int * year,
int * month,
int * day )
extern

Check if specified integer contains date in format YYYYMMDD.

Returns
Returns 0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise <>0.
Parameters
dateintInteger to be checked; not changed in this routine
yearYear is written in this pointer; enter NULL if not needed
monthMonth is written in this pointer; enter NULL if not needed
dayDay is written in this pointer; enter NULL if not needed

Definition at line 230 of file datetime.c.

239 {
240 int Y, M, D, n;
241 if(dateint<1201 || dateint>99991231) return 1;
242 n=dateint/100; D=dateint-100*n; Y=n/100; M=n-100*Y;
243 if(M>12 || D>31) return -1;
244 if(Y<1 || M<1 || D<1) return -1;
245 if(year!=NULL) *year=Y;
246 if(month!=NULL) *month=M;
247 if(day!=NULL) *day=D;
248 return 0;
249}

Referenced by ecat7ReadMainheader().

◆ isdatetime()

int isdatetime ( char * str,
char * intdate )
extern

Check if specified string contains date and time in correct format (YYYY-MM-DD hh:mm:ss, DD.MM.YYYY hh:mm:ss, or DD.MM.YY hh:mm:ss). String must start with date, but any contents after time is ignored.

Returns
Returns 0 if date and time are in correct format, <0 if format is correct but date or time is invalid, and otherwise <>0.
Parameters
strString to be checked; not changed in this routine
intdatePointer to allocated string where date and time is written in international format (YYYY-MM-DD hh:mm:ss); enter NULL, if not needed.

Definition at line 280 of file datetime.c.

287 {
288 int ret1, ret2, len, type=0;
289 char correct_date[20], *time_ptr=NULL;
290
291 len=strlen(str); if(len<17) return 1;
292 if((ret1=isdate(str))<=0) {
293 type=1; strncpy(correct_date, str, 10); correct_date[10]=(char)0;
294 } else if((ret1=isdate2(str, correct_date))<=0) type=2;
295 else if((ret1=isdate3(str, correct_date))<=0) type=3;
296 else {return 2;}
297 if(type==1 || type==2) {
298 if(str[10]!=' ' && str[10]!='\t') return 3;
299 time_ptr=str+11;
300 } else if(type==3) {
301 if(str[8]!=' ' && str[8]!='\t') return 3;
302 time_ptr=str+9;
303 }
304 ret2=istime(time_ptr);
305 if(ret1>0) {
306 if(ret2>=0) return(100*ret1+ret2); else return(100*ret2);
307 }
308 if(ret2>0) return(10*ret2);
309 if(ret1<0) {if(ret2<0) return(-3); else return(-1);}
310 if(ret2<0) return(-2);
311 if(intdate!=NULL) {
312 sprintf(intdate, "%10.10s %8.8s", correct_date, time_ptr);
313 }
314 return 0;
315}

Referenced by dcmDT2intl(), and get_datetime().

◆ isleapyear()

int isleapyear ( long int year)
extern

Check for leap year.

Returns
Nonzero if 'year' is a leap year.
Parameters
yearYear

Definition at line 423 of file datetime.c.

426 {
427 return (year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0);
428}

Referenced by time_to_tm().

◆ istime()

int istime ( char * str)
extern

Check if specified string contains time in correct format (hh:mm:ss). String must start with time, but any contents after it is ignored.

Returns
Returns 0 if time is in correct format, -1 if format is correct but time is invalid, and otherwise <>0.
Parameters
strString to be checked; not changed in this routine

Definition at line 259 of file datetime.c.

262 {
263 int h, m, s, n;
264 if(strlen(str)<8) return 1;
265 if(str[2]!=':' || str[5]!=':') return 2;
266 if(strncasecmp(str, "hh:mm:ss", 8)==0) return -1;
267 n=sscanf(str, "%d:%d:%d", &h, &m, &s); if(n!=3) return 3;
268 if(h<0 || h>23 || m<0 || m>59 || s<0 || s>59) return -1;
269 return 0;
270}

Referenced by dcmTM2intl(), iftRead(), and isdatetime().

◆ leaps_between()

long int leaps_between ( long int year1,
long int year2 )
extern

Calculates the number of leap years between year1 and year2.

Returns
Nr of leap years.
Parameters
year1Year 1
year2Year 2

Definition at line 435 of file datetime.c.

440 {
441 long int leaps1, leaps2;
442
443 leaps1 = math_div(year1-1, 4) - math_div(year1-1, 100) + math_div(year1-1, 400);
444 leaps2 = math_div(year2-1, 4) - math_div(year2-1, 100) + math_div(year2-1, 400);
445 return(leaps2-leaps1);
446}
long int math_div(long int a, long int b)
Definition datetime.c:409

Referenced by time_to_tm().

◆ libpet_idcrypt_version()

const char * libpet_idcrypt_version ( void )
extern

Return idcrypt module version info

Definition at line 15 of file idcrypt.c.

15 {
16 return "2004-12-14";
17}

◆ little_endian()

int little_endian ( )
extern

Check whether current platform uses little endian byte order. See H&S Sec. 6.1.2 pp. 163-4.

Returns
Returns 1, if current platform is little endian, and 0 if not.

Definition at line 14 of file swap.c.

15{
16 int x=1;
17 if(*(char *)&x==1) return(1); else return(0);
18}

Referenced by anaReadHeader(), anaReadImagedata(), anaWriteHeader(), dcmFileWrite(), dcmitemGetInt(), dcmitemGetReal(), dcmReadFileTag(), dcmReadFileVL(), dcmReadFileVRVL(), dcmValueString(), dcmWriteFileTag(), dcmWriteFileVRVL(), ecat63Create(), ecat63Matenter(), ecat63ReadAttnheader(), ecat63ReadImageheader(), ecat63ReadMainheader(), ecat63ReadMatdata(), ecat63ReadMatlist(), ecat63ReadNormheader(), ecat63ReadScanheader(), ecat63WriteAttnheader(), ecat63WriteImageheader(), ecat63WriteMainheader(), ecat63WriteMatdata(), ecat63WriteNormheader(), ecat63WriteScanheader(), ecat7Create(), ecat7EnterMatrix(), ecat7Read2DNormheader(), ecat7Read2DScanheader(), ecat7ReadAttenheader(), ecat7ReadImageheader(), ecat7ReadMainheader(), ecat7ReadMatlist(), ecat7ReadMatrixdata(), ecat7ReadNormheader(), ecat7ReadPolmapheader(), ecat7ReadScanheader(), ecat7Write2DNormheader(), ecat7Write2DScanheader(), ecat7WriteAttenheader(), ecat7WriteImageheader(), ecat7WriteMainheader(), ecat7WriteMatrixdata(), ecat7WriteNormheader(), ecat7WritePolmapheader(), ecat7WriteScanheader(), hrrtMakeCalHdr(), imgSetNiftiHeader(), imgWriteAnalyze(), imgWriteAnalyzeFrame(), niftiReadHeader(), niftiReadImagedata(), niftiWriteHeader(), tiffWriteImg(), and upetReadImagedata().

◆ localtime_r()

struct tm * localtime_r ( const time_t * t,
struct tm * tm )
extern

Convert time_t to local time in struct tm.

This version of localtime_r function is here for systems (at least Windows) where it is not defined. Uses localtime, which is threadsafe in Windows.

See also
gmtime_r
Returns
Pointer to struct tm, or null in case of an error.
Parameters
tPointer to time_t; do not give pointer to int here, like &e7mhdr.scan_start_time
tmPointer to struct tm, to be filled here

Definition at line 46 of file datetime.c.

52 {
53 struct tm *ltm=localtime(t);
54 if(ltm==NULL || tm==NULL) return(NULL);
55 *tm=*ltm; tm->tm_isdst=-1;
56 return tm;
57}

◆ math_div()

long int math_div ( long int a,
long int b )
extern

Division for long integers.

Returns
a/b
Parameters
aA/b
ba/B

Definition at line 409 of file datetime.c.

414 {
415 return a/b - (a%b < 0);
416}

Referenced by leaps_between(), and time_to_tm().

◆ petCunit()

char * petCunit ( int cunit)
extern

Return pointer to string describing the calibration data units.

See also
petCunitId, petTunitId, petTunit, cunitFromFilename
Parameters
cunitindex of PET_data units_string[].

Definition at line 211 of file petunits.c.

214 {
215 int n=0;
216 while(cunit_string[n]!=0) n++;
217 if(cunit<0 || cunit>n-1) return(cunit_string[CUNIT_UNKNOWN]);
218 else return(cunit_string[cunit]);
219}

Referenced by csv2dft_linkset(), dftGetPmodTitle(), and imgUnit().

◆ petCunitId()

int petCunitId ( const char * unit)
extern

Identify the specified units string as PET data unit.

Returns
Returns the unit id number.
See also
petTunitId, petCunit, petTunit, cunitFromFilename

Definition at line 74 of file petunits.c.

75{
76 if(unit==NULL) return CUNIT_UNKNOWN;
77 if(strlen(unit)==0) return CUNIT_UNKNOWN;
78 else if(strcasecmp(unit, "unknown")==0) return CUNIT_UNKNOWN;
79 else if(strcasecmp(unit, "cnts/sec")==0) return CUNIT_CPS;
80 else if(strcasecmp(unit, "counts/sec")==0) return CUNIT_CPS;
81 else if(strcasecmp(unit, "ECAT counts/sec")==0) return CUNIT_CPS;
82 else if(strcasecmp(unit, "cps")==0) return CUNIT_CPS;
83 else if(strcasecmp(unit, "counts")==0) return CUNIT_COUNTS;
84 else if(strcasecmp(unit, "cnts")==0) return CUNIT_COUNTS;
85 else if(strcasecmp(unit, "kBq/cc")==0) return CUNIT_KBQ_PER_ML;
86 else if(strcasecmp(unit, "kBqcc")==0) return CUNIT_KBQ_PER_ML;
87 else if(strcasecmp(unit, "kBq/mL")==0) return CUNIT_KBQ_PER_ML;
88 else if(strcasecmp(unit, "kBqmL")==0) return CUNIT_KBQ_PER_ML;
89 else if(strcasecmp(unit, "sec*kBq/cc")==0) return CUNIT_SEC_KBQ_PER_ML;
90 else if(strcasecmp(unit, "sec*kBq/mL")==0) return CUNIT_SEC_KBQ_PER_ML;
91 else if(strcasecmp(unit, "integral")==0) return CUNIT_SEC_KBQ_PER_ML;
92 else if(strcasecmp(unit, "1/sec")==0) return CUNIT_PER_SEC;
93 else if(strcasecmp(unit, "1/s")==0) return CUNIT_PER_SEC;
94 else if(strcasecmp(unit, "s-1")==0) return CUNIT_PER_SEC;
95 else if(strcasecmp(unit, "1/min")==0) return CUNIT_PER_MIN;
96 else if(strcasecmp(unit, "min-1")==0) return CUNIT_PER_MIN;
97 else if(strcasecmp(unit, "mL/mL")==0) return CUNIT_ML_PER_ML;
98 else if(strcasecmp(unit, "mL/cc")==0) return CUNIT_ML_PER_ML;
99 else if(strcasecmp(unit, "mL/dL")==0) return CUNIT_ML_PER_DL;
100 else if(strcasecmp(unit, "mL/100mL")==0) return CUNIT_ML_PER_DL;
101 else if(strcasecmp(unit, "mL/(mL*min)")==0) return CUNIT_ML_PER_ML_PER_MIN;
102 else if(strcasecmp(unit, "mL/(min*mL)")==0) return CUNIT_ML_PER_ML_PER_MIN;
103 else if(strcasecmp(unit, "mL/(cc*min)")==0) return CUNIT_ML_PER_ML_PER_MIN;
104 else if(strcasecmp(unit, "mL/(min*cc)")==0) return CUNIT_ML_PER_ML_PER_MIN;
105 else if(strcasecmp(unit, "mL/mL/min")==0) return CUNIT_ML_PER_ML_PER_MIN;
106 else if(strcasecmp(unit, "mL/min/mL")==0) return CUNIT_ML_PER_ML_PER_MIN;
107 else if(strcasecmp(unit, "mL/cc/min")==0) return CUNIT_ML_PER_ML_PER_MIN;
108 else if(strcasecmp(unit, "mL/min/cc")==0) return CUNIT_ML_PER_ML_PER_MIN;
109 else if(strcasecmp(unit, "mL/(dL*min)")==0) return CUNIT_ML_PER_DL_PER_MIN;
110 else if(strcasecmp(unit, "mL/(min*dL)")==0) return CUNIT_ML_PER_DL_PER_MIN;
111 else if(strcasecmp(unit, "mL/(100mL*min)")==0) return CUNIT_ML_PER_DL_PER_MIN;
112 else if(strcasecmp(unit, "mL/(min*100mL)")==0) return CUNIT_ML_PER_DL_PER_MIN;
113 else if(strcasecmp(unit, "mL/dL/min")==0) return CUNIT_ML_PER_DL_PER_MIN;
114 else if(strcasecmp(unit, "mL/min/dL")==0) return CUNIT_ML_PER_DL_PER_MIN;
115 else if(strcasecmp(unit, "mL/100mL/min")==0) return CUNIT_ML_PER_DL_PER_MIN;
116 else if(strcasecmp(unit, "mL/min/100mL")==0) return CUNIT_ML_PER_DL_PER_MIN;
117 else if(strcasecmp(unit, "unitless")==0) return CUNIT_UNITLESS;
118 else if(strcasecmp(unit, "1/1")==0) return CUNIT_UNITLESS;
119 else if(strcasecmp(unit, "Hounsfield Unit")==0) return CUNIT_HU;
120 else if(strcasecmp(unit, "HU")==0) return CUNIT_HU;
121 else if(strcasecmp(unit, "nCi/cc")==0) return CUNIT_NCI_PER_ML;
122 else if(strcasecmp(unit, "nCicc")==0) return CUNIT_NCI_PER_ML;
123 else if(strcasecmp(unit, "nCi/mL")==0) return CUNIT_NCI_PER_ML;
124 else if(strcasecmp(unit, "nCimL")==0) return CUNIT_NCI_PER_ML;
125 else if(strcasecmp(unit, "MBq/cc")==0) return CUNIT_MBQ_PER_ML;
126 else if(strcasecmp(unit, "MBqcc")==0) return CUNIT_MBQ_PER_ML;
127 else if(strcasecmp(unit, "MBq/mL")==0) return CUNIT_MBQ_PER_ML;
128 else if(strcasecmp(unit, "MBqmL")==0) return CUNIT_MBQ_PER_ML;
129 else if(strcasecmp(unit, "Bq/cc")==0) return CUNIT_BQ_PER_ML;
130 else if(strcasecmp(unit, "Bqcc")==0) return CUNIT_BQ_PER_ML;
131 else if(strcasecmp(unit, "Bq/mL")==0) return CUNIT_BQ_PER_ML;
132 else if(strcasecmp(unit, "BqmL")==0) return CUNIT_BQ_PER_ML;
133 else if(strcasecmp(unit, "uCi/cc")==0) return CUNIT_UCI_PER_ML;
134 else if(strcasecmp(unit, "uCicc")==0) return CUNIT_UCI_PER_ML;
135 else if(strcasecmp(unit, "uCi/mL")==0) return CUNIT_UCI_PER_ML;
136 else if(strcasecmp(unit, "uCimL")==0) return CUNIT_UCI_PER_ML;
137 else if(strcasecmp(unit, "umol/(100g*min)")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
138 else if(strcasecmp(unit, "umol/(min*100g)")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
139 else if(strcasecmp(unit, "umol/100g/min")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
140 else if(strcasecmp(unit, "umol/min/100g")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
141 else if(strcasecmp(unit, "umol/(dL*min)")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
142 else if(strcasecmp(unit, "umol/(min*dL)")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
143 else if(strcasecmp(unit, "umol/dL/min")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
144 else if(strcasecmp(unit, "umol/min/dL")==0) return CUNIT_UMOL_PER_MIN_PER_100G;
145 else if(strcasecmp(unit, "mg/(100g*min)")==0) return CUNIT_MG_PER_MIN_PER_100G;
146 else if(strcasecmp(unit, "mg/(min*100g)")==0) return CUNIT_MG_PER_MIN_PER_100G;
147 else if(strcasecmp(unit, "mg/100g/min")==0) return CUNIT_MG_PER_MIN_PER_100G;
148 else if(strcasecmp(unit, "mg/min/100g")==0) return CUNIT_MG_PER_MIN_PER_100G;
149 else if(strcasecmp(unit, "mg/(dL*min)")==0) return CUNIT_MG_PER_MIN_PER_100G;
150 else if(strcasecmp(unit, "mg/(min*dL)")==0) return CUNIT_MG_PER_MIN_PER_100G;
151 else if(strcasecmp(unit, "mg/dL/min")==0) return CUNIT_MG_PER_MIN_PER_100G;
152 else if(strcasecmp(unit, "mg/min/dL")==0) return CUNIT_MG_PER_MIN_PER_100G;
153 else if(strcasecmp(unit, "%")==0) return CUNIT_PERCENTAGE;
154 else if(strcasecmp(unit, "kcps")==0) return CUNIT_KCPS;
155 else if(strcasecmp(unit, "min*kBq/cc")==0) return CUNIT_MIN_KBQ_PER_ML;
156 else if(strcasecmp(unit, "min*kBq/mL")==0) return CUNIT_MIN_KBQ_PER_ML;
157 else if(strcasecmp(unit, "Bq")==0) return CUNIT_BQ;
158 else if(strcasecmp(unit, "kBq")==0) return CUNIT_KBQ;
159 else if(strcasecmp(unit, "MBq")==0) return CUNIT_MBQ;
160 else if(strcasecmp(unit, "GBq")==0) return CUNIT_GBQ;
161 else if(strcasecmp(unit, "nCi")==0) return CUNIT_NCI;
162 else if(strcasecmp(unit, "uCi")==0) return CUNIT_UCI;
163 else if(strcasecmp(unit, "mCi")==0) return CUNIT_MCI;
164 else if(strcasecmp(unit, "%ID")==0) return CUNIT_PID;
165 else if(strcasecmp(unit, "% ID")==0) return CUNIT_PID;
166 else if(strcasecmp(unit, "%ID/g")==0) return CUNIT_PIDM;
167 else if(strcasecmp(unit, "% ID/g")==0) return CUNIT_PIDM;
168 else if(strcasecmp(unit, "%ID/mL")==0) return CUNIT_PIDV;
169 else if(strcasecmp(unit, "% ID/mL")==0) return CUNIT_PIDV;
170 else if(strcasecmp(unit, "%ID/cc")==0) return CUNIT_PIDV;
171 else if(strcasecmp(unit, "% ID/cc")==0) return CUNIT_PIDV;
172 else if(strcasecmp(unit, "g/mL")==0) return CUNIT_G_PER_ML;
173 else if(strcasecmp(unit, "g/cc")==0) return CUNIT_G_PER_ML;
174 else if(strncasecmp(unit, "SUV", 3)==0) return CUNIT_G_PER_ML;
175 else if(strcasecmp(unit, "mL/g")==0) return CUNIT_ML_PER_G;
176 else if(strcasecmp(unit, "cc/g")==0) return CUNIT_ML_PER_G;
177
178 return CUNIT_UNKNOWN;
179}

Referenced by csv2dft_a(), csv2dft_linkset(), cunit_check_dft_vs_img(), dftGetPmodTitle(), dftReadinput(), dftReadModelingData(), dftReadReference(), dftSetComments(), dftTimeIntegral(), dftUnitConversion(), and dftWrite().

◆ petTunit()

char * petTunit ( int tunit)
extern

Return pointer to string describing the time unit.

See also
petCunitId, petTunitId, petCunit, cunitFromFilename
Parameters
tunitindex of PET_time unit_string[].

Definition at line 226 of file petunits.c.

229 {
230 int n=0;
231 while(tunit_string[n]!=0) n++;
232 if(tunit<0 || tunit>n-1) return(tunit_string[TUNIT_UNKNOWN]);
233 else return(tunit_string[tunit]);
234}

Referenced by check_times_dft_vs_dft(), csv2dft_linkset(), dftInterpolateForIMG(), dftMatchTimeunits(), dftSetComments(), dftWrite(), dftWriteHTML(), fitWrite(), imgReadModelingData(), res_allocate_with_dft(), and tsvRead().

◆ petTunitId()

int petTunitId ( const char * timeunit)
extern

Identifies the specified string as PET time (x axis) units.

Returns
Returns the timeunit id number.
See also
petCunitId, petCunit, petTunit, cunitFromFilename

Definition at line 187 of file petunits.c.

188{
189 if(timeunit==NULL) return TUNIT_UNKNOWN;
190 if(strlen(timeunit)==0) return TUNIT_UNKNOWN;
191 else if(strcasecmp(timeunit, "unknown")==0) return TUNIT_UNKNOWN;
192 else if(strncasecmp(timeunit, "seconds", 3)==0) return TUNIT_SEC;
193 else if(strcmp(timeunit, "s")==0) return TUNIT_SEC;
194 else if(strncasecmp(timeunit, "minutes", 3)==0) return TUNIT_MIN;
195 else if(strcasecmp(timeunit, "um")==0) return TUNIT_UM;
196 else if(strcasecmp(timeunit, "mm")==0) return TUNIT_MM;
197 else if(strcasecmp(timeunit, "cm")==0) return TUNIT_CM;
198 else if(strcasecmp(timeunit, "m")==0) return TUNIT_M;
199 else if(strcasecmp(timeunit, "h")==0) return TUNIT_HOUR;
200 else if(strcasecmp(timeunit, "months")==0) return TUNIT_MONTH;
201 else if(strcasecmp(timeunit, "y")==0) return TUNIT_YEAR;
202 else if(strcasecmp(timeunit, "msec")==0) return TUNIT_MSEC;
203 return TUNIT_UNKNOWN;
204}

Referenced by csv2dft_linkset(), dft_fill_hdr_from_IFT(), dftGetPmodTitle(), dftRead(), dftTimeunitToDFT(), and fitRead().

◆ printf32bits()

void printf32bits ( void * buf)
extern

Printfs as bit string the 32-bit variable pointed to by buf. Far from being optimized, thus only for testing and development purposes.

Parameters
bufPointer to memory

Definition at line 133 of file swap.c.

133 {
134 unsigned int u, i;
135 int j;
136
137 memcpy(&u, buf, 4);
138 for(i=32; i>0; i--) {
139 j=i-1;if(i<32 && (i%8)==0) printf(" ");
140 if(u & (1L<<j)) printf("1"); else printf("0");
141 }
142 printf("\n");
143}

◆ readStrtokens()

int readStrtokens ( const char * filename,
char *** toklist )
extern

Read list of string tokens from specified file Remember to free the memory of string list.

Returns
Returns the nr of tokens or <0 in case of an error.
Parameters
filenameName of file to read
toklistPointer to list of strings read and allocated here

Definition at line 181 of file readfile.c.

186 {
187 int i, ret, nr=0;
188 char *allfile, *cptr;
189 static char **list;
190 FILE *fp;
191
192 /* Check arguments */
193 if(strlen(filename)<1) return(-1);
194 /* Open file */
195 fp=fopen(filename, "r"); if(fp==NULL) return(-2);
196 /* Get file size */
197 nr=0; while((ret=fgetc(fp))!=EOF) nr++; rewind(fp);
198 if(nr<1) {fclose(fp); return(0);}
199 /* Allocate memory for file contents */
200 allfile=(char*)malloc((nr+1)*sizeof(char));
201 if(allfile==NULL) {fclose(fp); return(-4);}
202 /* Read file contents */
203 i=0; while((ret=fgetc(fp))!=EOF && i<nr) allfile[i++]=(char)ret;
204 fclose(fp); allfile[i]=(char)0;
205 /* Get the number of tokens */
206 cptr=allfile; nr=0;
207 while(1) {
208 i=strspn(cptr, " ;,|\t\n\r"); cptr+=i;
209 i=strcspn(cptr, " ;,|\t\n\r"); cptr+=i;
210 if(i==0 || *cptr==0) break; else nr++;
211 }
212 /*printf("Nr of tokens in %s: %d\n", filename, nr);*/
213 /* Allocate memory for array of strings */
214 list=(char**)malloc(nr*sizeof(char*));
215 if(list==NULL) {free(allfile); return(-5);}
216 /* and then fill the list */
217 cptr=strtok(allfile, " ;,|\t\n\r");
218 for(i=0; i<nr; i++) {
219 if(cptr==NULL) {
220 for(--i; i>=0; i--) free(list[i]);
221 free(list); free(allfile);
222 return(-8);
223 }
224 list[i]=(char*)malloc( (strlen(cptr)+1)*sizeof(char) );
225 if(list[i]==NULL) {
226 for(--i; i>=0; i--) free(list[i]);
227 free(list); free(allfile);
228 return(-9);
229 }
230 strcpy(list[i], cptr);
231 cptr=strtok(NULL, " ;,|\t\n\r");
232 }
233 free(allfile);
234 *toklist=list;
235 return(nr);
236}

◆ rnameCatenate()

int rnameCatenate ( char * rname,
int max_rname_len,
char * name1,
char * name2,
char * name3,
char space )
extern

Construct full TAC name from up to three subnames.

Returns
Returns 0 when successful, <>0 if failed.
Parameters
rnamePointer to string of length max_rname_len, in where the full name will be placed
max_rname_lenLength of full TAC name, not including null char
name1Pointer to 1st subname (anatomical region); NULL if not available
name2Pointer to 1st subname (usually hemisphere); NULL if not available
name3Pointer to 1st subname (usually image plane); NULL if not available
spaceSpacing character, for example ' ', '_', or '-'

Definition at line 189 of file rname.c.

203 {
204 unsigned int len, rlen;
205
206 if(rname==NULL || max_rname_len<1) return 1;
207 if(name1==NULL && name2==NULL && name3==NULL) return 2;
208
209 strcpy(rname, "");
210
211 len=strlen(name1);
212 if(len>0 && len<(unsigned int)max_rname_len && strcmp(name1, ".")!=0)
213 strcpy(rname, name1);
214
215 len=strlen(name2); rlen=strlen(rname);
216 if(len>0 && (len+strlen(rname)+1)<(unsigned int)max_rname_len
217 && strcmp(name2, ".")!=0) {
218 if(rlen>0) {rname[rlen]=(char)space; rname[rlen+1]=(char)0;}
219 strcat(rname, name2);
220 }
221
222 len=strlen(name3); rlen=strlen(rname);
223 if(len>0 && (len+strlen(rname)+1)<(unsigned int)max_rname_len
224 && strcmp(name3, ".")!=0) {
225 if(rlen>0) {rname[rlen]=(char)space; rname[rlen+1]=(char)0;}
226 strcat(rname, name3);
227 }
228
229 if(strlen(rname)<1) return 3;
230 return 0;
231}

Referenced by dftRead(), dftRNameSimplify(), fitRead(), and resRead().

◆ rnameMatch()

int rnameMatch ( char * rname,
int rnr,
char * test_str )
extern

Test whether region name or number matches with a test string. Test string can contain wildcards. If test string contains only one subname, it is tested against whole rname. If it contains 2-3 subnames, those are tested against the corresponding tokens in rname. Subname '.' stands for empty name. Number is tested only if test string contains one token of all digits.

Returns
Returns 1, in case of match, or 0 if not matched.
Parameters
rnameRegion name which is tested
rnrRegion number (1..)
test_strTest string

Definition at line 144 of file rname.c.

151 {
152 char region[3][MAX_REGIONNAME_LEN+1];
153 char test[3][MAX_REGIONNAME_LEN+1];
154 unsigned int ni, m, rtoknr=0, ttoknr=0;
155
156 /* Check the input */
157 if(rname==NULL || strlen(rname)<1) return(0);
158 if(test_str==NULL || strlen(test_str)<1) return(0);
159 /* Split region names into 1-3 subnames */
160 rtoknr=rnameSplit(rname, region[0], region[1], region[2], MAX_REGIONNAME_LEN);
161 ttoknr=rnameSplit(test_str, test[0], test[1], test[2], MAX_REGIONNAME_LEN);
162 if(rtoknr==0 || ttoknr==0) return(0);
163 /* If more than one subname to test for, then test against corresponding
164 subnames */
165 if(ttoknr>1) {
166 for(ni=0; ni<ttoknr; ni++) {
167 if( strcmp(test[ni], ".") && fncasematch(test[ni], region[ni])==0 ) {
168 return(0);}
169 }
170 return(1);
171 }
172 /* If just one subname to test for */
173 /* If it contains only digits, then we assume that it is region number */
174 for(ni=m=0; ni<strlen(test[0]); ni++)
175 if(isdigit((int)test[0][ni])==0) {m++; break;}
176 if(m==0 && (ni=atoi(test[0]))>0) { /* it indeed is an acceptable number */
177 if((unsigned int)rnr==ni) return(1); else return(0);
178 }
179 /* It is name; chack if it is found anywhere in the region name */
180 for(ni=0; ni<rtoknr; ni++) if(fncasematch(test[0], region[ni])) return(1);
181 return(0);
182}
int fncasematch(const char *fname, const char *key)
Definition filename.c:100
#define MAX_REGIONNAME_LEN
Definition libtpcmisc.h:154
int rnameSplit(char *rname, char *name1, char *name2, char *name3, int max_name_len)
Definition rname.c:14

Referenced by dftSelectRegions(), and resSelectRegions().

◆ rnameRmDots()

int rnameRmDots ( char * rname1,
char * rname2 )
extern

Region name may contain dots marking non-existing identification of hemisphere or image plane etc. This function removes the dots and extra space characters.

Returns
Returns <0 in case of an error, otherwise the number of tokens that were left.
Parameters
rname1String which contains the original region name; the modified string is written in next string, if pointer to it is given next.
rname2Pointer to previously allocated string, into which the modified region name will be written. Enter NULL, if previous string is to be modified instead.

Definition at line 99 of file rname.c.

107 {
108 char *temp, *out, *cptr, *lptr;
109 int len, c=0;
110
111 if(rname1==NULL) return -1;
112 len=strlen(rname1);
113 if(len<1) {if(rname2!=NULL) strcpy(rname2, ""); return 0;}
114 temp=malloc(len+1); if(temp==NULL) return -3;
115 strcpy(temp, rname1);
116 if(rname2==NULL) out=rname1; else out=rname2;
117 strcpy(out, "");
118
119 /* remove dots and extra spaces */
120 lptr=temp;
121 cptr=strtok(lptr, " \t\n\r");
122 while(cptr!=NULL) {
123 if(strcmp(cptr, ".")!=0) {
124 if(strlen(out)>0) strcat(out, " ");
125 strcat(out, cptr); c++;
126 }
127 cptr=strtok(NULL, " \t\n\r");
128 }
129 free(temp);
130 return c;
131}

Referenced by plot_fit_svg(), plot_fitrange_svg(), plot_svg(), res2ift(), and rnameSplit().

◆ rnameSplit()

int rnameSplit ( char * rname,
char * name1,
char * name2,
char * name3,
int max_name_len )
extern

Split region name into 1-3 subparts of given max length.

Returns
Returns the number of subparts.
Parameters
rnameRegion name to split (string is not edited)
name1Pointer to 1st subname (anatomical region)
name2Pointer to 2nd subname (usually hemisphere)
name3Pointer to 3rd subname (usually image plane)
max_name_lenMax length of subnames, excluding terminal null

Definition at line 14 of file rname.c.

25 {
26 char temp[MAX_REGIONNAME_LEN+1], temp2[MAX_REGIONNAME_LEN+1];
27 char *cptr, *lptr, space[64];
28 int nr;
29
30 if(rname==NULL || name1==NULL || name2==NULL || name3==NULL) return(0);
31#if(0)
32 printf(" rname := '%s'\n", rname);
33#endif
34 if(max_name_len<1) return(0);
35 name1[0]=name2[0]=name3[0]=(char)0;
36 strncpy(temp, rname, MAX_REGIONNAME_LEN); temp[MAX_REGIONNAME_LEN]=(char)0;
37
38 /* Try to divide long name with only upper case letters as possible dividers */
39 if((int)strlen(rname)>max_name_len) {
40 int nr1, nr2;
41 strcpy(space, " _-."); nr1=strChrCount(temp, space);
42 nr2=strUppercaseCount(temp+1); // not counting first character if that is uppercase
43 if(nr1==0 && nr2>0 && nr2<=3) {
44 nr=0;
45 int len=strlen(temp);
46 int i=1, n=0;
47 cptr=temp;
48 while(i<len && !isupper(temp[i])) i++;
49 n=i; if(n>max_name_len) n=max_name_len;
50 strncpy(name1, cptr, n); name1[n]=(char)0; nr++;
51 cptr=temp+i; n=0;
52 while(i<len && (!isupper(temp[i]) || n==0)) {i++; n++;}
53 if(n>max_name_len) n=max_name_len;
54 if(n>0) {
55 strncpy(name2, cptr, n); name2[n]=(char)0; nr++;
56 cptr=temp+i; n=0;
57 while(i<len && (!isupper(temp[i]) || n==0)) {i++; n++;}
58 if(n>max_name_len) n=max_name_len;
59 if(n>0) {strncpy(name3, cptr, n); name3[n]=(char)0; nr++;}
60 }
61#if(0)
62 printf(" -> subnames := '%s' '%s' '%s'\n", name1, name2, name3);
63#endif
64 return(nr);
65 }
66 }
67
68 nr=rnameRmDots(temp, temp2);
69#if(0)
70 printf("temp = '%s'\n", temp);
71 printf("temp2 = '%s'\n", temp2);
72#endif
73 strcpy(space, " \t");
74 if(nr<3) {
75 if(strChrCount(temp2, space)<2) strcat(space, "_");
76 if(strChrCount(temp2, space)<2) strcat(space, "-");
77 }
78 strcat(space, "\n\r");
79 nr=0; lptr=temp;
80 cptr=strtok(lptr, space); if(cptr==NULL) return(nr);
81 strncpy(name1, cptr, max_name_len); name1[max_name_len]=(char)0; nr++;
82 cptr=strtok(NULL, space); if(cptr==NULL) return(nr);
83 strncpy(name2, cptr, max_name_len); name2[max_name_len]=(char)0; nr++;
84 cptr=strtok(NULL, space); if(cptr==NULL) return(nr);
85 strncpy(name3, cptr, max_name_len); name3[max_name_len]=(char)0; nr++;
86#if(0)
87 printf(" -> subnames := '%s' '%s' '%s'\n", name1, name2, name3);
88#endif
89 return(nr);
90}
int strChrCount(const char *str1, const char *str2)
Definition strext.c:126
int strUppercaseCount(const char *s)
Definition strext.c:146
int rnameRmDots(char *rname1, char *rname2)
Definition rname.c:99

Referenced by csv2dft_a(), csv2dft_b(), csv2dft_linkset(), csv2dft_mat(), dft_fill_hdr_from_IFT(), dftGetPmodTitle(), resRead(), and rnameMatch().

◆ roinameExists()

int roinameExists ( char * roiname)
extern

Verifies whether TAC name exists or not.

TAC name string may contain only delimiters like '.', '_', '-', or spaces. Those cases are interpreted as no name in this function.

Returns
1 if valid name exists, 0 if not.
Parameters
roinameROI name string; not edited

Definition at line 241 of file rname.c.

244 {
245 if(roiname==NULL) return(0);
246 size_t len, n;
247 len=strlen(roiname); if(len==0) return(0);
248 n=strspn(roiname, " _-.\t"); if(n==len) return(0);
249 return(1);
250}

◆ statSortDouble()

void statSortDouble ( double * data,
unsigned int n,
int order )
extern

Sort the given double array into ascending or descending order.

Author
Vesa Oikonen
Parameters
dataPointer to data array of size n
nLength of data array
orderAscending (0) or descending (<>0) order

Definition at line 267 of file doubleutil.c.

274 {
275 if(n<2 || data==NULL) return;
276 if(order==0) qsort(data, n, sizeof(double), statDoubleCompAsc);
277 else qsort(data, n, sizeof(float), statDoubleCompDesc);
278}

◆ statSortFloat()

void statSortFloat ( float * data,
unsigned int n,
int order )
extern

Sort the given double list into ascending or descending order.

Author
Vesa Oikonen

Sort the given float array into ascending or descending order.

Author
Vesa Oikonen
Parameters
dataPointer to data array of size n
nLength of data array
orderAscending (0) or descending (<>0) order

Definition at line 76 of file imgqntls.c.

83 {
84 if(n<2 || data==NULL) return;
85 if(order==0) qsort(data, n, sizeof(float), statFloatCompAsc);
86 else qsort(data, n, sizeof(float), statFloatCompDesc);
87}

◆ str_token_list_add()

int str_token_list_add ( STR_TOKEN_LIST * lst,
char * new_item )
extern

Put a string in STR_TOKEN_LIST.

Returns
Returns 0, if successful, and <>0 in case of an error.
Parameters
lstList that has to be initialized beforehand.
new_itemString that is added to list.

Definition at line 42 of file readfile.c.

47 {
48 int i;
49 const int add_nr=10;
50
51 if(lst==NULL || new_item==NULL || strlen(new_item)<1) return(1);
52 if(lst->list_size<=lst->token_nr) {
53 lst->tok=realloc(lst->tok, sizeof(char*)*(lst->list_size+add_nr));
54 if(lst->tok==NULL) return(2);
55 for(i=lst->list_size; i<lst->list_size+add_nr; i++) lst->tok[i]=NULL;
56 lst->list_size+=add_nr;
57 }
58 lst->tok[lst->token_nr]=strdup(new_item);
59 if(lst->tok[lst->token_nr]==NULL) return(3);
60 lst->token_nr++;
61
62 return(0);
63}

Referenced by str_token_list_read(), and textfileReadLines().

◆ str_token_list_del()

int str_token_list_del ( STR_TOKEN_LIST * lst,
int item )
extern

Remove the specified string item from the STR_TOKEN_LIST.

Returns
Returns 0, if successful, and <>0 in case of an error.
Parameters
lstList that has to be initialized beforehand.
itemItem number to remove (1..item_nr).

Definition at line 70 of file readfile.c.

75 {
76 //printf("str_token_list_del(list with %d items, %d)\n", lst->token_nr, item);
77 if(lst==NULL || item<1 || item>lst->token_nr) return(1);
78 if(lst->tok[item-1]!=NULL) free(lst->tok[item-1]);
79 for(int i=item; i<lst->token_nr; i++) {
80 //printf(" index %d -> %d\n", i, i-1);
81 lst->tok[i-1]=lst->tok[i]; lst->tok[i]=NULL;
82 }
83 lst->token_nr--;
84 return(0);
85}

Referenced by sifRead().

◆ str_token_list_empty()

void str_token_list_empty ( STR_TOKEN_LIST * lst)
extern

Free memory allocated for STR_TOKEN_LIST. All contents are destroyed.

Parameters
lstPointer to list to be emptied.

Definition at line 26 of file readfile.c.

29 {
30 for(int i=0; i<lst->list_size; i++)
31 if(lst->tok[i]!=NULL) free(lst->tok[i]);
32 if(lst->tok!=NULL) free(lst->tok);
33 lst->tok=NULL;
34 lst->list_size=0; lst->token_nr=0;
35}

Referenced by roi_read(), sifRead(), str_token_list_read(), and textfileReadLines().

◆ str_token_list_init()

void str_token_list_init ( STR_TOKEN_LIST * lst)
extern

Initiate STR_TOKEN_LIST structure. This should be called once before first use.

Parameters
lstPointer to list to be initiated.

Definition at line 13 of file readfile.c.

16 {
17 memset(lst, 0, sizeof(STR_TOKEN_LIST));
18 lst->list_size=0; lst->token_nr=0; lst->tok=NULL;
19}

Referenced by roi_read(), and sifRead().

◆ str_token_list_read()

int str_token_list_read ( const char * filename,
STR_TOKEN_LIST * lst )
extern

Read all string tokens from text file into STR_TOKEN_LIST. List needs to be initialized. Previous contents are deleted.

Returns
Returns 0, if successful, and <>0 in case of an error.
Parameters
filenameName of text file to read
lstToken list is allocated by this function.

Definition at line 93 of file readfile.c.

98 {
99 int i, ret, nr=0;
100 char *allfile, *cptr;
101 FILE *fp;
102
103 if(lst==NULL || filename==NULL || strlen(filename)<1) return(1);
105
106 /* Open file */
107 fp=fopen(filename, "r"); if(fp==NULL) return(2);
108 /* Get file size */
109 nr=0; while((ret=fgetc(fp))!=EOF) nr++; rewind(fp);
110 if(nr<1) {fclose(fp); return(0);}
111 /* Allocate memory for file contents */
112 allfile=(char*)malloc((nr+1)*sizeof(char));
113 if(allfile==NULL) {fclose(fp); return(3);}
114 /* Read file contents */
115 i=0; while((ret=fgetc(fp))!=EOF && i<nr) allfile[i++]=(char)ret;
116 fclose(fp); allfile[i]=(char)0;
117 /* and then fill the list */
118 cptr=strtok(allfile, " ;,|\t\n\r");
119 if(cptr==NULL) {free(allfile); return(4);}
120 do {
121 if(str_token_list_add(lst, cptr)) {free(allfile); return(10);}
122 cptr=strtok(NULL, " ;,|\t\n\r");
123 } while(cptr!=NULL);
124 free(allfile);
125
126 return(0);
127}
void str_token_list_empty(STR_TOKEN_LIST *lst)
Definition readfile.c:26
int str_token_list_add(STR_TOKEN_LIST *lst, char *new_item)
Definition readfile.c:42

◆ strcasestr()

char * strcasestr ( const char * haystack,
const char * needle )
extern

Case-insensitive version of strstr().

Returns
a pointer to the beginning of the first occurrence, or NULL if not found.
Parameters
haystackPointer to string in which sub-string needle is searched.
needlePointer to sub-string which is searched for in source string haystack.

Definition at line 279 of file strext.c.

284 {
285 if(!haystack || !*haystack || !needle || !*needle) return 0;
286
287 const char *s=haystack, *p=needle;
288 do {
289 if(!*p) return(char*)haystack;
290 if((*p==*s) || (tolower(*p)==tolower(*s))) {
291 p++; s++;
292 } else {
293 p=needle; if(!*s) return(NULL);
294 s=++haystack;
295 }
296 } while(1);
297 return *p ? NULL : (char*)haystack;
298}

Referenced by cunitFromFilename(), dftFormat(), iftReadValue(), and resWriteHTML_table().

◆ strChrCount()

int strChrCount ( const char * str1,
const char * str2 )
extern

Count how many times specified characters are found in a string. Search is case-sensitive.

See also
strTokenNr, strReplaceChar, strUppercaseCount
Returns
Returns the nr of characters of str2 found in str1.
Parameters
str1String to search for characters; not modified.
str2String containing characters which are searched for; not modified.

Definition at line 126 of file strext.c.

131 {
132 unsigned int n=0, i, j;
133 if(str1==NULL || str2==NULL || strlen(str1)==0 || strlen(str2)==0) return n;
134 for(i=0; i<strlen(str1); i++)
135 for(j=0; j<strlen(str2); j++)
136 if(str1[i]==str2[j]) n++;
137 return n;
138}

Referenced by rnameSplit().

◆ strCleanForXML()

void strCleanForXML ( char * s)
extern

Remove from string those characters that would require encoding in XML. Replaced by character '-'.

See also
strEncodeForXML
Parameters
sPointer to the string to be cleaned.

Definition at line 402 of file strext.c.

405 {
406 if(s==NULL || *s=='\0') return;
407 strReplaceChar(s, '&', '-');
408 strReplaceChar(s, '\'', '-');
409 strReplaceChar(s, '\"', '-');
410 strReplaceChar(s, '<', '-');
411 strReplaceChar(s, '>', '-');
412 return;
413}
void strReplaceChar(char *str, char c1, char c2)
Definition strext.c:159

◆ strCleanSpaces()

int strCleanSpaces ( char * s)
extern

Removes any initial and trailing space characters from specified string s.

Space characters in the middle of the string are not removed.

Returns
0 when successful, otherwise >0.
Author
Vesa Oikonen
Parameters
sPointer to the string.

Definition at line 343 of file strext.c.

346 {
347 if(s==NULL) return 0;
348 int len=strlen(s); if(len<0) return 0;
349 char *s2; s2=strdup(s); if(s2==NULL) return(1);
350 int n=strncpyCleanSpaces(s2, s, len+1);
351 if(n<1) strcpy(s, ""); else strcpy(s, s2);
352 free(s2);
353 return 0;
354}
int strncpyCleanSpaces(char *s1, const char *s2, int maxlen)
Definition strext.c:308

Referenced by csvRead().

◆ strEncodeForXML()

char * strEncodeForXML ( const char * s)
extern

Encode special characters for XML, including SVG.

Postcondition
Free the memory of returned string pointer.
Returns
Returns pointer to encoded string. NULL is returned in case of an error, or if encoding is not necessary.
See also
svg_str_encode
Parameters
sPointer to the string to be encoded.

Definition at line 364 of file strext.c.

367 {
368 if(s==NULL) return(NULL);
369 /* Count the characters needing encoding */
370 int n=0;
371 for(size_t i=0; i<strlen(s); i++) {
372 if(s[i]=='&') {n++; continue;}
373 if(s[i]=='\'') {n++; continue;}
374 if(s[i]=='\"') {n++; continue;}
375 if(s[i]=='<') {n++; continue;}
376 if(s[i]=='>') {n++; continue;}
377 }
378 if(n==0) return(NULL);
379 /* Allocate memory for new string (one char to max 6 chars) */
380 n*=5; n+=strlen(s)+1;
381 char *ns=(char*)malloc(n*sizeof(char));
382 if(ns==NULL) return(NULL);
383 /* Process the string */
384 for(int i=0; i<n; i++) ns[i]=(char)0;
385 for(size_t i=0; i<strlen(s); i++) {
386 if(s[i]=='&') {strcat(ns, "&amp;"); continue;}
387 if(s[i]=='\'') {strcat(ns, "&apos;"); continue;}
388 if(s[i]=='\"') {strcat(ns, "&quot;"); continue;}
389 if(s[i]=='<') {strcat(ns, "&lt;"); continue;}
390 if(s[i]=='>') {strcat(ns, "&gt;"); continue;}
391 ns[strlen(ns)]=s[i];
392 }
393 return(ns);
394}

Referenced by dftWriteHTML(), and resWriteHTML_table().

◆ strlcat()

size_t strlcat ( char * dst,
const char * src,
size_t dstsize )
extern

Safer version of strncat. At most dstsize-1 characters are appended from the source string to destination string. Destination string will be NUL terminated, unless dstsize <= strlen(dst).

Remarks
Included in POSIX but not in GCC.
Returns
the size of the buffer that would have been needed for the destination string; if >=dstsize, then truncation occurred.
Parameters
dstDestination string.
srcSource string.
dstsizeThe actual length of buffer allocated for the destination string; for example, destination string has been allocated as char dst[dstsize];

Definition at line 206 of file strext.c.

214 {
215 char *d;
216 const char *s=src;
217 size_t dlen, n;
218
219 /* Find the current length of dst */
220 dlen=strnlen(dst, dstsize);
221 if(s==NULL) return(dlen);
222 n=dstsize-dlen;
223 if(n==0) return(dlen+strlen(s));
224 d=dst+dlen;
225 while(*s!='\0') {
226 if(n!=1) {*d=*s; d++; n--;}
227 s++;
228 }
229 *d='\0';
230 return(dlen+(s-src));
231}
size_t strnlen(const char *s, size_t n)
Definition strext.c:181

Referenced by anaExists(), backupExistingFile(), dftRead(), and hrrtMakeCalHdr().

◆ strlcpy()

size_t strlcpy ( char * dst,
const char * src,
size_t dstsize )
extern

Safer version of strncpy or strcpy.

At most dstsize-1 characters are copied from the source string to the destination string. Destination string will be NUL terminated.

Remarks
Included in POSIX but not in GCC.
Returns
the size of the buffer that would have been needed for the destination string; if >=dstsize, then truncation occurred.
Parameters
dstDestination string.
srcSource string.
dstsizeThe actual length of buffer allocated for the destination string; for example, destination string has been allocated as char dst[dstsize];

Definition at line 245 of file strext.c.

253 {
254 if(dstsize>0) dst[0]='\0';
255 if(strlen(src)==0) return(0);
256
257 char *d=dst;
258 const char *s=src;
259 size_t n;
260
261 /* Copy as many chars as allowed */
262 n=dstsize;
263 if(n!=0) while(--n!=0) {*d=*s; if(*d=='\0') {d++; s++; break;} d++; s++;}
264 if(n==0) { // not enough space, add NUL, and check how much space were needed
265 if(dstsize!=0) *d='\0';
266 while(*s++) {}
267 }
268 return(s-src-1);
269}

Referenced by anaEditHeader(), anaExists(), backupExistingFile(), csv2dft_b(), csv2dft_mat(), dcmAddItem(), dcmFileRead(), dft_fill_hdr_from_IFT(), dftAllocateWithIMG(), dftRead(), dftWrite(), ecat63AddImg(), ecat63EditMHeader(), ecat63ReadAllToImg(), ecat63ReadPlaneToImg(), ecat63WriteAllImg(), ecat7EditMHeader(), ecat7EditVHeader(), ecatCopy63to7mainheader(), ecatCopy7to63mainheader(), fitRead(), hrrtMakeCalHdr(), img2sif(), imgGetAnalyzeHeader(), imgGetEcat63MHeader(), imgGetEcat7MHeader(), imgGetMicropetSIF(), imgReadAnalyze(), imgReadAnalyzeHeader(), imgReadNiftiHeader(), imgSetEcat63MHeader(), imgSetEcat7MHeader(), imgSetNiftiHeader(), imgWriteAnalyze(), niftiCreateFNames(), niftiExists(), niftiHeaderToIFT(), resRead(), selectEcat931Calibrationfile(), sif2img(), strncpyCleanSpaces(), strTokenDup(), strTokenNCpy(), studynr_from_fname2(), studynr_in_fname(), upetExists(), and xelRead().

◆ strnCopyClean()

int strnCopyClean ( char * str1,
const char * str2,
int maxlen )
extern

Copy str2 to str1, removing any quotation marks around the string, and making sure that string fits to str2.

Returns
Returns the length of the new string str2.
Parameters
str1Pointer to pre-allocated result string with length of at least maxlen characters, including NULL character
str2Pointer to the original string; not changed in this function
maxlenMax length of str1, including the end NULL

Definition at line 52 of file quots.c.

60 {
61 char *cptr;
62 int i;
63
64 if(str1==NULL || maxlen<1) return(0);
65 str1[0]=(char)0; if(str2==NULL || strlen(str2)<1) return(0);
66 cptr=(char*)str2; cptr+=strspn(str2, "\"\'\t\n\r ");
67 strncpy(str1, cptr, maxlen-1); str1[maxlen-1]=(char)0;
68 i=strlen(str1); if(i<1) return(0);
69 cptr=str1+(i-1);
70 while(i>0) {
71 if(*cptr!='\"' && *cptr!='\'' && *cptr!='\t' && *cptr!='\n' &&
72 *cptr!='\r' && *cptr!=' ')
73 break;
74 i--; str1[i]=(char)0; cptr--;
75 }
76 return(i);
77}

Referenced by upetHeaderReadParameter().

◆ strncpyCleanSpaces()

int strncpyCleanSpaces ( char * s1,
const char * s2,
int maxlen )
extern

Version of strncpy() which as usual copies s2 to s1, but without any space characters or line end characters that may be around the string s2.

Returns
the length of the new string s1.
Author
Vesa Oikonen
Parameters
s1Pointer to pre-allocated result string with length of at least maxlen characters, including NULL character.
s2Pointer to the original string.
maxlenMax length of s1, including the trailing zero.

Definition at line 308 of file strext.c.

316 {
317 if(s1==NULL) return(0);
318 s1[0]=(char)0; if(maxlen<1) return(0);
319 if(maxlen<2) {strcpy(s1, ""); return(0);}
320 if(s2==NULL || strlen(s2)<1) return(0);
321
322 char *cptr;
323 int i;
324
325 cptr=(char*)s2; cptr+=strspn(s2, "\t\n\r ");
326 strlcpy(s1, cptr, maxlen); i=strlen(s1); if(i<1) return(0);
327 cptr=s1+(i-1);
328 while(i>0) {
329 if(*cptr!='\t' && *cptr!='\n' && *cptr!='\r' && *cptr!=' ') break;
330 i--; s1[i]=(char)0; cptr--;
331 }
332 return(i);
333}
size_t strlcpy(char *dst, const char *src, size_t dstsize)
Definition strext.c:245

Referenced by roi_read(), roiRead(), and strCleanSpaces().

◆ strnlen()

size_t strnlen ( const char * s,
size_t n )
extern

Safer version of strlen, in case the argument s is not NUL terminated string. Computes the length of string s, but never scans beyond the n first bytes of the string.

Remarks
Included in POSIX and GCC, so this implementation may not be needed.
Returns
same as strlen() or n, whichever is smaller.
Parameters
sPointer to string, or character array, that may not be NULL terminated.
nThe actual length of buffer allocated for the string; for example, string could have been allocated as char s[n];

Definition at line 181 of file strext.c.

187 {
188 if(s==NULL) return(0);
189 char *ps=(char*)s;
190 size_t i=0;
191 while(i<n && *ps!='\0') {i++; ps++;}
192 return(i);
193}

Referenced by csv2dft_mat(), dcmAddItem(), dcmDA2intl(), dcmDT2intl(), dcmFileRead(), dcmFileWrite(), dcmSOPIdentify(), dcmSOPUIDName(), dcmTM2intl(), dcmTrUID(), dftWrite(), irdRead(), sifRead(), strlcat(), and tpcHtmlUsage().

◆ strPtrToNextValue()

char * strPtrToNextValue ( char * str,
char ** nxtp )
extern

This function searches the given string for a string representation of numerical value, possibly with decimal and exponent part. Returns also pointer to the string right after where the numerical value ended, and from where the next number can be searched. Return Returns pointer to start of the next string, or NULL if not found.

Parameters
strPointer to string where numerical values are searched; not changed.
nxtpObligatory pointer to string pointer, which will be set to point to the first character after value string, or to NULL if string ends.

Definition at line 134 of file decpoint.c.

140 {
141 char *cptr, *strt;
142 unsigned int i, j, n=0;
143
144 // search the start
145 if(str==NULL || strlen(str)<1) {*nxtp=NULL; return NULL;}
146 // find the index where number might start
147 cptr=str;
148 do {
149 i=strcspn(cptr, "+-0123456789"); if(i==strlen(cptr)) {*nxtp=NULL; return NULL;}
150 strt=cptr+i;
151 // any previous character must be a separator
152 if(i>0) {cptr=strt-1; i=strcspn(cptr, " \t,;"); if(i>0) cptr+=i;}
153 } while(i>0);
154 // get past + and - ; if more than one, that is an error
155 cptr=strt; if(*cptr=='-' || *cptr=='+') {n++; cptr++;}
156 // get past first set of numbers
157 i=strspn(cptr, "0123456789"); n+=i;
158 if(i<1) {*nxtp=cptr; return NULL;}
159 cptr+=i; n+=i;
160 // get past decimal separator
161 i=strspn(cptr, ",.");
162 if(i==0) { // there was none, thus we're done
163 *nxtp=cptr; return strt;
164 } else if(i>1) { // can't be more than one decimal separator
165 *nxtp=cptr; return strt;
166 }
167 cptr+=1; n+=1;
168 // after decimal separator we must have numbers again
169 i=strspn(cptr, "0123456789");
170 if(i<1) { // what was thought to be decimal separator was not that
171 *nxtp=cptr-1; return strt;
172 }
173 cptr+=i; n+=i;
174 // check if we have exponent part
175 if(*cptr=='E' || *cptr=='e') i=1; else i=0;
176 // if not, then we're done
177 if(i==0) {*nxtp=cptr; return strt;}
178 cptr+=1;
179 // we may have signed exponent
180 if(*cptr=='-' || *cptr=='+') {cptr+=1; i++;}
181 // after exponent we must have numbers again
182 j=strspn(cptr, "0123456789");
183 if(j<1) { // what was thought to be exponent was not that
184 *nxtp=cptr-i; return strt;
185 }
186 cptr+=j; n+=j;
187 // now this must be the end
188 *nxtp=cptr;
189 return strt;
190}

◆ strReplaceChar()

void strReplaceChar ( char * str,
char c1,
char c2 )
extern

Replace certain characters in string with another character.

Parameters
strPointer to string in which the character is replaced.
c1Character to be replaced.
c2Character to use instead. If NULL, then only the first character is replaced.

Definition at line 159 of file strext.c.

166 {
167 char *cptr;
168 if(strlen(str)==0) return;
169 while((cptr=strchr(str, c1))!=NULL) *cptr=c2;
170 return;
171}

Referenced by dftWrite(), fitRead(), roi_read(), roiRead(), and strCleanForXML().

◆ strstr_noquotation()

char * strstr_noquotation ( const char * str1,
const char * str2 )
extern

The strstr_noquotation() function returns a pointer to the first occurrence in the string pointed to by str1, excluding parts that are inside quotation marks "" or '', of the string pointed to by str2.

Returns
Returns NULL pointer if no match is found, or if found, then pointer to the first occurrence.
Parameters
str1Pointer to string to be searched
str2Pointer to string with quotation marks

Definition at line 17 of file quots.c.

22 {
23 unsigned int i, test_len;
24 unsigned int single_quotation=0;
25 unsigned int double_quotation=0;
26 char *cptr;
27
28 if(str1==NULL) return((char*)NULL);
29 if(str2==NULL) return((char*)str1);
30 test_len=strlen(str2); if(test_len<1) return((char*)str1);
31 for(i=0, cptr=(char*)str1; i<strlen(str1); i++, cptr++) {
32 if(*cptr=='\'') {
33 if(single_quotation==0) single_quotation=1; else single_quotation=0;
34 continue;
35 }
36 if(*cptr=='\"') {
37 if(double_quotation==0) double_quotation=1; else double_quotation=0;
38 continue;
39 }
40 if(single_quotation==1 || double_quotation==1) continue;
41 if(strncmp(cptr, str2, test_len)==0) return(cptr);
42 }
43 return((char*)NULL);
44}

Referenced by iftRead().

◆ strTokenDup()

char * strTokenDup ( const char * s1,
const char * s2,
int * next )
extern

Search the string s1 for the first token. The characters making up the string s2 are the delimiters that determine the tokens.

Returns
Returns pointer to a copy of the token string, or NULL in case of an error or if no token found.
Postcondition
Remember to free the memory from the returned pointer after last use.
Author
Vesa Oikonen
Parameters
s1String from where tokens are searched; not modified in any way.
s2String containing character delimiters.
nextIndex of s1 where the token ended; set to NULL, if not needed.

Definition at line 89 of file strext.c.

96 {
97 if(next!=NULL) *next=0;
98 if(s1==NULL) return NULL;
99
100 char *s3=NULL, *cptr;
101 size_t j;
102
103 /* If no delimiters, then return copy of s1 */
104 if(s2==NULL || strlen(s2)<1) {
105 s3=strdup(s1); if(next!=NULL) *next=strlen(s1);
106 return s3;
107 }
108 /* Pass initial delimiter characters */
109 cptr=(char*)s1; j=strspn(cptr, s2); cptr+=j; if(next!=NULL) *next=j;
110 /* calculate characters between delimiters */
111 j=strcspn(cptr, s2); if(j==0) {return NULL;}
112 if(next!=NULL) *next+=j;
113 /* Allocate space for token */
114 s3=calloc(j+1, sizeof(char)); if(s3==NULL) return NULL;
115 strlcpy(s3, cptr, j+1);
116 return s3;
117}

Referenced by fitRead(), and textfileReadLines().

◆ strTokenNCpy()

int strTokenNCpy ( const char * str1,
const char * str2,
int i,
char * str3,
int count )
extern

The strTokenNCpy() function copies the i'th token in the string pointed to by str1 into string pointed to by str3. The characters making up the string pointed to by str2 are the delimiters that determine the token.

See also
strTokenNr, strTokenDup
Returns
Returns the length of token, 0 if no token(s) found.
Parameters
str1String from where tokens are searched; not modified in any way.
str2String containing character delimiters.
iToken number to copy (1..nr of tokens).
str3String array into where the token is copied; string will be null terminated.
countLength of str3, including terminal null

Definition at line 45 of file strext.c.

56 {
57 int j=0, n=0;
58 char *cptr;
59 if(str1==NULL || str2==NULL || strlen(str1)==0 || strlen(str2)==0) return(0);
60 if(i<1 || str3==NULL || count<2) return(0);
61
62 cptr=(char*)str1;
63 do {
64 // pass delimiter characters
65 j=strspn(cptr, str2); cptr+=j;
66 // pass characters between delimiters
67 j=strcspn(cptr, str2); if(j>0) n++;
68 // if this is the required token nr, then stop here
69 if(n==i) {
70 if(j>count-1) j=count-1;
71 strlcpy(str3, cptr, j+1); //strncpy(str3, cptr, j); str3[j]=(char)0;
72 break;
73 }
74 cptr+=j;
75 } while(j>0);
76 if(n>i) {str3[0]=(char)0; return(0);}
77 return(j);
78}

Referenced by fitRead(), integerListAddFromString(), integerListExpandFromString(), pxlRead(), resRead(), and roi_read().

◆ strTokenNr()

int strTokenNr ( const char * str1,
const char * str2 )
extern

The strTokenNr() function returns the number of tokens in the string pointed to by str1. The characters making up the string pointed to by str2 are the delimiters that determine the token.

See also
strTokenNCpy, strChrCount
Returns
Returns the nr of tokens.
Parameters
str1String from where tokens are calculated; not modified in any way.
str2String containing character delimiters.

Definition at line 17 of file strext.c.

22 {
23 int i=0, n=0;
24 char *cptr;
25 if(str1==NULL || str2==NULL || strlen(str1)==0 || strlen(str2)==0) return(0);
26
27 cptr=(char*)str1;
28 do {
29 // pass delimiter characters
30 i=strspn(cptr, str2); cptr+=i;
31 // pass characters between delimiters
32 i=strcspn(cptr, str2); cptr+=i; if(i>0) n++;
33 } while(i>0);
34 return(n);
35}

Referenced by fitRead(), integerListAddFromString(), integerListExpandFromString(), pxlRead(), resRead(), and roi_read().

◆ strUppercaseCount()

int strUppercaseCount ( const char * s)
extern

Count how many upper case characters are found in string.

Returns
Returns the nr of upper case characters found in s.
See also
strChrCount
Parameters
sString to search for upper case characters; not modified.

Definition at line 146 of file strext.c.

149 {
150 unsigned int n=0, i;
151 if(s==NULL || strlen(s)==0) return (int)n;
152 for(i=0; i<strlen(s); i++) if(isupper(s[i])) n++;
153 return (int)n;
154}

Referenced by rnameSplit().

◆ studynr_from_fname()

int studynr_from_fname ( char * fname,
char * studynr )
extern

Extract study number (max MAX_STUDYNR_LEN chars) from filename. This function removes initial zeroes from the number part, and converts uppercase letters to lowercase, if necessary.

Returns
0 if successful.
Parameters
fnameFilename may include path. Filename is not modified.
studynrPointer for the resulting study number. Memory (>=MAX_STUDYNR_LEN+1 chars) for it must be allocated before calling this.

Definition at line 119 of file studynr.c.

125 {
126 return studynr_from_fname2(fname, studynr, 0);
127}
int studynr_from_fname2(char *fname, char *studynr, int force)
Definition studynr.c:67

Referenced by cptReadOne(), dftRead(), imgMicropetCTToEcat7(), imgMicropetPETToEcat7(), resFName2study(), resRead(), tsvRead(), and xelRead().

◆ studynr_from_fname2()

int studynr_from_fname2 ( char * fname,
char * studynr,
int force )
extern

Extract study number (max MAX_STUDYNR_LEN chars) from filename.

This function removes initial zeroes from the number part, and converts uppercase letters to lowercase, if necessary.

Returns
Returns 0 if successful.
Parameters
fnameFilename, which may include the path. Filename is not modified.
studynrPointer for the resulting study number. Memory (>=MAX_STUDYNR_LEN+1 chars) must be allocated before calling this.
forceValidity of studynr is verified (0) or not verified (1)

Definition at line 67 of file studynr.c.

75 {
76 unsigned int i;
77 char *cptr;
78
79 //printf("studynr_from_fname2()\n");
80
81 if(fname==NULL || studynr==NULL) return(1);
82 strcpy(studynr, "");
83
84 /* At first try if studynr_in_fname() works */
85 if(studynr_in_fname(fname, studynr)==0) return(0);
86
87 /* Remove path */
88 cptr=strrchr(fname, '/'); if(cptr==NULL) cptr=strrchr(fname, '\\');
89 if(cptr==NULL) cptr=fname; else cptr++;
90 //i=strlen(cptr); if(i>MAX_STUDYNR_LEN) i=MAX_STUDYNR_LEN;
91 strlcpy(studynr, cptr, MAX_STUDYNR_LEN); //studynr[i]=(char)0;
92 if(force!=0) return(0);
93
94 /* Check that first character is a letter */
95 if(!isalpha((int)studynr[0])) {strcpy(studynr, ""); return(4);}
96 /* Remove everything after the letter+digit parts */
97 for(i=1; i<strlen(studynr); i++) if(!isalpha((int)studynr[i])) break;
98 for(; i<strlen(studynr); i++) if(!isdigit((int)studynr[i])) break;
99 studynr[i]=(char)0;
100 /* Check the length of the study number */
101 if(strlen(studynr)<2) {strcpy(studynr, ""); return(5);}
102 /* Remove initial zeroes from the number part */
103 if(studynr_rm_zeroes(studynr)!=0) {strcpy(studynr, ""); return(6);}
104 /* Convert characters to lower case */
105 if(studynr_to_lowercase(studynr)!=0) {strcpy(studynr, ""); return(7);}
106 /* Check the validity of the study number */
107 if(!studynr_validity_check(studynr)) {strcpy(studynr, ""); return(8);}
108 return(0);
109}
#define MAX_STUDYNR_LEN
Definition libtpcmisc.h:163
int studynr_in_fname(char *fname, char *studynr)
Definition studynr.c:18
int studynr_to_lowercase(char *studynr)
Definition studynr.c:233
int studynr_rm_zeroes(char *studynr)
Definition studynr.c:211
int studynr_validity_check(char *studynr)
Definition studynr.c:196

Referenced by imgGetMicropetHeader(), and studynr_from_fname().

◆ studynr_in_fname()

int studynr_in_fname ( char * fname,
char * studynr )
extern

Find study number (max MAX_STUDYNR_LEN chars) inside filename; Study number must contain 1-5 letters followed by 1-5 digits, if such string is not found then error code is returned.

Initial zeroes are removed if necessary and uppercase letters are changed to lowercase.

Returns
Returns 0 if successful, otherwise <>0.
Parameters
fnameFilename may include path. Filename is not modified.
studynrPointer to string (>=MAX_STUDYNR_LEN+1 chars) where the resulting study number is written.

Definition at line 18 of file studynr.c.

24 {
25 unsigned int i;
26 int ret;
27 char *cptr, *lptr, temp[FILENAME_MAX], temp2[FILENAME_MAX];
28
29 //printf("studynr_in_filename(%s, string)\n", fname);
30 if(fname==NULL || studynr==NULL) return(1);
31 for(i=0; i<=MAX_STUDYNR_LEN; i++) studynr[i]=(char)0;
32 /* Remove path */
33 cptr=strrchr(fname, '/'); if(cptr==NULL) cptr=strrchr(fname, '\\');
34 if(cptr==NULL) cptr=fname; else cptr++;
35 //i=strlen(cptr); if(i>FILENAME_MAX-1) i=FILENAME_MAX-1;
36 strlcpy(temp, cptr, FILENAME_MAX); lptr=temp;
37 /* Verify tokens in filename whether they are valid as study number */
38 cptr=strtok(lptr, "_-+{}!~.()");
39 while(cptr!=NULL && !studynr[0]) {
40 strcpy(temp2, cptr);
41 /* Remove everything after the letter+digit parts */
42 for(i=1; i<strlen(temp2); i++) if(!isalpha((int)temp2[i])) break;
43 for(; i<strlen(temp2); i++) if(!isdigit((int)temp2[i])) break;
44 temp2[i]=(char)0;
45 /* Only then check it */
46 ret=studynr_validity_check2(temp2, 1);
47 if(ret==1) {
48 strcpy(studynr, temp2);
49 if(studynr_rm_zeroes(studynr)!=0) strcpy(studynr, "");
50 if(studynr_to_lowercase(studynr)!=0) strcpy(studynr, "");
51 }
52 cptr=strtok(NULL, "_-+{}!~.()");
53 }
54 if(!studynr[0]) return(2);
55 return 0;
56}
int studynr_validity_check2(char *studynr, int zero_ok)
Definition studynr.c:166

Referenced by studynr_from_fname2().

◆ studynr_match()

int studynr_match ( char * studynr1,
char * studynr2 )
extern

Check whether two valid study numbers are the same. If either of study numbers is shorter than the other, the end parts are compared; thus study numbers that are changed by SPM can be matched. Argument strings are not modified.

Parameters
studynr1compared number
studynr2compared number
Returns
1 if study numbers match exactly, 2 if the match is probable, and zero, if no match is found.

Definition at line 142 of file studynr.c.

142 {
143 int len1, len2;
144 char *cptr1, *cptr2;
145
146 len1=strlen(studynr1); if(len1<2 || len1>MAX_STUDYNR_LEN) return(0);
147 len2=strlen(studynr2); if(len2<2 || len2>MAX_STUDYNR_LEN) return(0);
148 if(len1==len2 && strcmp(studynr1, studynr2)==0) return(1);
149 if(len2>len1) cptr2=studynr2+len2-len1; else cptr2=studynr2;
150 if(len1>len2) cptr1=studynr1+len1-len2; else cptr1=studynr1;
151 if(strcasecmp(cptr1, cptr2)==0) return(2);
152 return(0);
153}

◆ studynr_rm_zeroes()

int studynr_rm_zeroes ( char * studynr)
extern

Remove zeroes from the number part of the PET study number.

Parameters
studynrmodified study number.
Returns
nonzero in case of failure.

Definition at line 211 of file studynr.c.

211 {
212 int i, j, len;
213
214 len=strlen(studynr); if(len<2) return(1);
215 if(isdigit((int)studynr[0])) return(2);
216 if(!isdigit((int)studynr[len-1])) return(3);
217 for(i=1; i<len; i++) if(isdigit((int)studynr[i])) break;
218 for(j=i; j<len; j++) if(studynr[j]!='0') break;
219 if(i==j) return(0); /* no initial zeroes */
220 for(;j<=len; i++, j++) studynr[i]=studynr[j];
221 return(0);
222}

Referenced by studynr_from_fname2(), and studynr_in_fname().

◆ studynr_to_lowercase()

int studynr_to_lowercase ( char * studynr)
extern

Convert the PET study number letters to lowercase. Conversion is not done to non-valid study number.

Parameters
studynrmodified study number.
Returns
nonzero in case of failure.

Definition at line 233 of file studynr.c.

233 {
234 int i, len;
235
236 len=strlen(studynr); if(len<2) return(1);
237 if(isdigit((int)studynr[0])) return(2);
238 if(!isdigit((int)studynr[len-1])) return(3);
239 for(i=0; i<len; i++) {
240 if(isdigit((int)studynr[i])) break;
241 studynr[i]=(char)tolower((int)studynr[i]);
242 }
243 return(0);
244}

Referenced by studynr_from_fname2(), and studynr_in_fname().

◆ studynr_validity_check()

int studynr_validity_check ( char * studynr)
extern

Check that the argument string is a valid TPC study number.

Valid study number here is defined as containing 1-5 letters (upper- or lowercase) followed by at least 1 digit, with total length of max 10 characters.

Returns
1 if study number is valid, zero if not valid or in case of failure.
Parameters
studynrEvaluated study number; not modified.

Definition at line 196 of file studynr.c.

199 {
200 return studynr_validity_check2(studynr, 0);
201}

Referenced by ecat63ReadAllToImg(), ecat63ReadPlaneToImg(), imgGetEcat63MHeader(), imgGetEcat7MHeader(), and studynr_from_fname2().

◆ studynr_validity_check2()

int studynr_validity_check2 ( char * studynr,
int zero_ok )
extern

Check that the argument string is a valid TPC study number.

Valid study number here is defined as containing 1-5 letters (upper- or lowercase) followed by at least 1 digit, with total length of max 10 characters.

Returns
1 if study number is valid, zero if not valid or in case of failure.
Parameters
studynrString to be evaluated as study number. Not modified here.
zero_okNumber part of study number may start with zero (1) or may not (0)

Definition at line 166 of file studynr.c.

171 {
172 int i, j, len;
173
174 len=strlen(studynr); if(len<2 || len>MAX_STUDYNR_LEN) return(0);
175 for(i=0; i<len; i++) if(!isalnum((int)studynr[i])) return(0);
176 for(i=0; i<len; i++) if(!isalpha((int)studynr[i])) break;
177 if(i<1 || i>5) return(0);
178 if(zero_ok==0 && studynr[i]=='0') return(0); /* first digit must be >0 */
179 for(j=0; (i+j)<len; j++) if(!isdigit((int)studynr[i+j])) return(0);
180 //if(j<1 || j>5) return(0);
181 if(j<1 || (i+j)>10) return(0);
182 return(1);
183}

Referenced by studynr_in_fname(), and studynr_validity_check().

◆ swabip()

◆ swap()

void swap ( void * from,
void * to,
int size )
extern

Swaps the specified short int, int, long int, float, or double from little endian to big endian or vice versa. Arguments are allowed to overlap.

Parameters
fromPointer to a short int, int, long int, float, or double variable
toPointer to a short int, int, long int, float, or double variable
sizeSize of from and to (byte nr) must be 1, 2, 4 or 8.

Definition at line 31 of file swap.c.

31 {
32 unsigned char c;
33 unsigned short int s;
34 unsigned long l;
35
36 switch(size) {
37 case 1:
38 *(char *)to=*(char *)from;
39 break;
40 case 2:
41 c=*(unsigned char *)from;
42 *(unsigned char *)to = *((unsigned char *)from+1);
43 *((unsigned char *)to+1) = c;
44 /*swab(from, to, size); // NOT ANSI */
45 break;
46 case 4:
47 s=*(unsigned short *)from;
48 *(unsigned short *)to = *((unsigned short *)from+1);
49 *((unsigned short *)to+1) = s;
50 swap((char*)to, (char*)to, 2);
51 swap((char*)((unsigned short *)to+1), (char*)((unsigned short *)to+1), 2);
52 break;
53 case 8:
54 l=*(unsigned long *)from;
55 *(unsigned long *)to = *((unsigned long *)from+1);
56 *((unsigned long *)to+1) = l;
57 swap((char *)to, (char *)to, 4);
58 swap((char*)((unsigned long *)to+1), (char*)((unsigned long *)to+1), 4);
59 break;
60 }
61}
void swap(void *from, void *to, int size)
Definition swap.c:31

Referenced by dcmitemGetInt(), dcmitemGetReal(), dcmReadFileTag(), dcmReadFileVL(), dcmReadFileVRVL(), dcmValueString(), dcmWriteFileVRVL(), intExpand(), and swap().

◆ swawbip()

void swawbip ( void * buf,
long long int size )
extern

◆ swawip()

void swawip ( void * buf,
long long int size )
extern

In-place swaw, switches words (but not bytes) from an array of 4-byte ints or floats.

Parameters
bufPointer to memory
sizeSize of buf in bytes

Definition at line 114 of file swap.c.

116 {
117 unsigned short int s, *sptr;
118
119 sptr=(unsigned short int*)buf;
120 for(long long i=0; i<size; i+=4, sptr+=2) {
121 s=sptr[0]; sptr[0]=sptr[1]; sptr[1]=s;
122 }
123}

Referenced by ecat63rFloat(), ecat63wFloat(), and ecat7rFloat().

◆ temp_roundf()

int temp_roundf ( float e)
extern

int roundf(float e) - Rounds up float e to nearest int

Parameters
efloat value
Returns
rounded integer

Definition at line 20 of file petc99.c.

21{
22#if defined(__STDC_VERSION__) && __STD_VERSION__>=199901L
23 return(roundf(e));
24#else
25 if(e<0.0) {
26 return (int)(e-0.5);
27 } else {
28 return (int)(e+0.5);
29 }
30#endif
31}

Referenced by bootstrap(), ecat63AddImg(), ecat63WriteAllImg(), ecat63WriteImageMatrix(), ecat63WriteScanMatrix(), ecat7Write2DScanMatrix(), ecat7WriteImageMatrix(), ecat7WritePolarmapMatrix(), ecat7WriteScanMatrix(), ecatCopy63to7imageheader(), img2svol(), imgMaskRoiNr(), imgSetAnalyzeHeader(), imgVoiMaskTAC(), imgWrite2DEcat7(), imgWriteAnalyze(), imgWriteAnalyzeFrame(), imgWriteEcat63Frame(), imgWriteEcat7(), imgWriteEcat7Frame(), imgWritePolarmap(), roi_onoff(), roiFillGaps(), and tsvRead().

◆ textfileReadLines()

int textfileReadLines ( const char * filename,
STR_TOKEN_LIST * lst )
extern

Read all lines from text file into STR_TOKEN_LIST. List needs to be initialized. Previous contents are deleted.

Returns
Returns 0, if successful, and <>0 in case of an error.
See also
str_token_list_init, str_token_list_empty
Parameters
filenameName of text file to read
lstToken list is allocated by this function.

Definition at line 136 of file readfile.c.

141 {
142 int i, ret, nr=0;
143 char *allfile, *cptr, *line;
144 FILE *fp;
145
146 if(lst==NULL || filename==NULL || strlen(filename)<1) return(1);
148
149 /* Open file */
150 fp=fopen(filename, "r"); if(fp==NULL) return(2);
151 /* Get file size */
152 nr=0; while((ret=fgetc(fp))!=EOF) nr++; rewind(fp);
153 if(nr<1) {fclose(fp); return(0);} //printf("nr=%d\n", nr);
154 /* Allocate memory for file contents */
155 allfile=(char*)malloc((nr+1)*sizeof(char));
156 if(allfile==NULL) {fclose(fp); return(3);}
157 /* Read file contents */
158 i=0; while((ret=fgetc(fp))!=EOF && i<nr) allfile[i++]=(char)ret;
159 fclose(fp); allfile[i]=(char)0;
160 /* and then fill the list */
161 int npos=0; cptr=allfile;
162 line=strTokenDup(cptr, "\n\r\0", &npos);
163 if(line==NULL) {free(allfile); return(4);}
164 do {
165 //printf("line='%s'\n", line);
166 if(str_token_list_add(lst, line)) {free(allfile); free(line); return(10);}
167 free(line); if(npos==0) break; cptr=cptr+npos;
168 line=strTokenDup(cptr, "\n\r\0", &npos);
169 } while(line!=NULL);
170 free(allfile);
171
172 return(0);
173}
char * strTokenDup(const char *s1, const char *s2, int *next)
Definition strext.c:89

Referenced by roi_read(), and sifRead().

◆ time_to_tm()

void time_to_tm ( time_t totalsecs,
int offset,
struct tm * result )
extern

Convert calendar time to local broken-down time. This function is copied from GNU C Library with tiny modifications.

Parameters
totalsecsnumber of seconds elapsed since 00:00:00 on January 1, 1970, UTC; can be negative to represent times before 1970
offsetoffset seconds adding to totalsecs (e.g. -timezone)
resultpointer to struct tm variable to receive broken-down time

Definition at line 452 of file datetime.c.

460 {
461 if(offset==0) {gmtime_r(&totalsecs, result); return;}
462
463
464 long int days, rem, y, yg;
465 const unsigned short *ip;
466
467 days=totalsecs/86400; rem=totalsecs%86400; rem+=offset;
468 while(rem<0) {rem+=86400; --days;}
469 while(rem>=86400) {rem-=86400; ++days;}
470 result->tm_hour=rem/3600;
471 rem%=3600; result->tm_min=rem/60;
472 result->tm_sec=rem%60;
473
474 /* January 1, 1970 was a Thursday. */
475 result->tm_wday=(4+days)%7;
476 if(result->tm_wday<0) result->tm_wday+=7;
477 y=1970;
478 while(days<0 || days>=(isleapyear(y)?366:365)) {
479 /* Guess a corrected year, assuming 365 days per year. */
480 yg=y+math_div(days, 365);
481 /* Adjust days and y to match the guessed year. */
482 days-=(yg-y)*365 + leaps_between(y, yg);
483 y=yg;
484 }
485 result->tm_year=y-1900; result->tm_yday=days;
486 ip=__mon_yday[isleapyear(y)];
487 for(y=11; days<ip[y]; y--) continue;
488 days-=ip[y];
489 result->tm_mon=y;
490 result->tm_mday=days+1;
491 result->tm_isdst=-1;
492#if defined(HAVE_TM_GMTOFF)
493 result->tm_gmtoff=0L;
494#endif
495}
int isleapyear(long int year)
Definition datetime.c:423
long int leaps_between(long int year1, long int year2)
Definition datetime.c:435

◆ timegm()

time_t timegm ( struct tm * tm)
extern

Inverse of gmtime, converting struct tm to time_t.

Otherwise same as mktime, except that mktime uses local time. Uses gmtime_r or gmtime_s, if available, otherwise gmtime, which is threadsafe in Windows.

Returns
Returns the time_t, or -1 in case of an error.
Parameters
tmPointer to struct tm

Definition at line 69 of file datetime.c.

72 {
73#ifdef HAVE_GMTIME_R
74 {
75 time_t temp_lt;
76 struct tm temp_gm;
77 if(!tm) temp_lt=0; else temp_lt=mktime(tm);
78 if(gmtime_r(&temp_lt, &temp_gm)==NULL) return((time_t)-1);
79 return(time_t)(temp_lt + (temp_lt - mktime(&temp_gm)));
80 }
81#endif
82
83#ifdef HAVE_GMTIME_S
84 {
85 time_t temp_lt;
86 struct tm temp_gm;
87 if(!tm) temp_lt=0; else temp_lt=mktime(tm);
88 if(gmtime_s(&temp_gm, &temp_lt)!=0) return(time_t)-1);
89 return(time_t)(temp_lt + (temp_lt - mktime(&temp_gm)));
90 }
91#endif
92
93 time_t temp_lt;
94 struct tm *temp_gm;
95 if(!tm) temp_lt=0; else {tm->tm_isdst=-1; temp_lt=mktime(tm);}
96 temp_gm=gmtime(&temp_lt); if(temp_gm) temp_gm->tm_isdst=-1;
97 return(time_t)(temp_lt + (temp_lt - mktime(temp_gm)));
98}

Referenced by ecat63Scanstarttime(), ecat63ScanstarttimeToTm(), ecat7EditMHeader(), fitRead(), get_datetime(), imgGetMicropetHeader(), resRead(), sifRead(), tmAdd(), and upetScanStart().

◆ tmAdd()

void tmAdd ( int s,
struct tm * d )
extern

Add given time in seconds to the date and time.

Parameters
sTime to add in seconds; can be negative
dPointer to tm struct

Definition at line 514 of file datetime.c.

519 {
520 if(d==NULL) return;
521 d->tm_sec+=s;
522 //mktime(d); // this automatically normalizes sec to hours etc if necessary
523 timegm(d); // this automatically normalizes sec to hours etc if necessary
524}

◆ tmDifference()

double tmDifference ( struct tm * tm1,
struct tm * tm0 )
extern

Calculate the difference in seconds between two given dates and times.

Returns
Returns tm1-tm0 in seconds.
Parameters
tm1Pointer to tm struct
tm0Pointer to tm struct

Definition at line 502 of file datetime.c.

507 {
508 return(difftime(mktime(tm1), mktime(tm0)));
509}

Referenced by selectEcat931Calibrationfile().

◆ tpcHtmlUsage()

int tpcHtmlUsage ( const char * program,
char * text[],
const char * path )
extern

Write program usage given as argument, plus program name, tpcclib version, and default copyright text, into HTML file.

  • Any string @P, separated by space characters, is replaced by program name in the output. It can only be used once per line.
  • When line contains text 'stdoptions', in place of that the description of standard command-line options '-h, -v, -q, -s etc' are displayed.
    Returns
    Returns 0 when successful.
    Author
    Vesa Oikonen
    See also
    tpcPrintUsage
Parameters
programProgram name, may contain extension and path.
textProgram usage text.
pathPath name where to create file programname.html; path may contain trailing '/' or '\'.

Definition at line 213 of file proginfo.c.

220 {
221 unsigned int len, i, j;
222 char *bprogram, *fname, *cptr, *line;
223 FILE *fp;
224
225 if(program==NULL || text==NULL || strnlen(program, 1)<1) return 1;
226
227 /* Clean program name */
228 bprogram=strdup(program);
229 filenameRmPath(bprogram); filenameRmExtension(bprogram);
230
231 /* Make file name */
232 fname=calloc(strlen(path)+1+strlen(bprogram)+5, sizeof(char));
233 if(fname==NULL) {free(bprogram); return 1;}
234 strcpy(fname, path); len=strlen(fname);
235 if(len>0 && (fname[len-1]=='/' || fname[len-1]=='\\')) fname[len-1]=(char)0;
236 len=strlen(fname); if(len>0) strcat(fname, "/");
237 strcat(fname, bprogram); strcat(fname, ".html");
238
239 //printf("fname := '%s'\n", fname);
240
241 /* Open file for write */
242 fp=stdout;
243
244 /* Write HTML header */
245 len=fprintf(fp, "<!DOCTYPE html>\n");
246 if(len<10) {free(bprogram); free(fname); return 2;}
247 fprintf(fp, "<html lang=\"en-GB\">\n");
248 fprintf(fp, "<head>\n");
249 fprintf(fp, " <meta charset=\"utf-8\">\n");
250 fprintf(fp, " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
251 fprintf(fp, " <title>%s</title>\n", bprogram);
252 fprintf(fp, " <style type=\"text/css\">\n");
253 fprintf(fp, " body {\n");
254 fprintf(fp, " margin-left: 2em;\n");
255 fprintf(fp, " font-family: monospace;\n");
256 fprintf(fp, " font-size: 1em;\n");
257 fprintf(fp, " }\n");
258 fprintf(fp, " h1 {\n");
259 fprintf(fp, " font-size: 1.3em;\n");
260 fprintf(fp, " margin-top: 1em;\n");
261 fprintf(fp, " margin-bottom: 1em;\n");
262 fprintf(fp, " }\n");
263 fprintf(fp, " footer {\n");
264 fprintf(fp, " border:1px solid gray;\n");
265 fprintf(fp, " font-size: 0.8em;\n");
266 fprintf(fp, " }\n");
267 fprintf(fp, " footer p {margin-left: 1em;}\n");
268 fprintf(fp, " </style>\n");
269 fprintf(fp, "</head>\n\n");
270
271 /* Write HTML body */
272 fprintf(fp, "<body>\n");
273
274 /* Write program name, version and copyright as title; */
275 /* replace (c) with html code when necessary */
276 fprintf(fp, "<h1>%s - tpcclib %d.%d.%d ", bprogram, tpcclib_VERSION_MAJOR,
277 tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
278 line=tpcclib_COPYRIGHT; len=strlen(line);
279 for(j=0; j<len; j++) {
280 if(strncasecmp(line+j, "(C)", 3)==0) {fputs("&copy;", fp); j+=2; continue;}
281 fputc(line[j], fp);
282 }
283 fputs("</h1>\n\n", fp);
284
285 /* Print usage */
286 fprintf(fp, "<pre>\n");
287 i=0; while(text[i]!=0) {
288 line=text[i];
289 /* If line contains string 'stdoptions' then print instead of it the
290 description of standard command-line options */
291 if(strstr(line, "stdoptions")) {
292 int j=0;
293 while(tpcstdoptions[j]!=0) fprintf(fp, "%s\n", tpcstdoptions[j++]);
294 i++; continue;
295 }
296
297 /* Process "See also" line: add links to other programs */
298 if(strstr(line, "See also: ")!=NULL) {
299 /* copy until the first ':' */
300 j=0; while(line[j]!='\0') {
301 fputc(line[j], fp);
302 j++; if(line[j-1]==':') break;
303 }
304 /* the rest of line with token */
305 char *tline; unsigned int n=0;
306 tline=strdup(line+j); cptr=strtok(tline, ", :;\t\n\r");
307 while(cptr!=NULL) {
308 if(n>0) fputc(',', fp);
309 fprintf(fp, " <a href=\"./%s.html\">%s</a>", cptr, cptr);
310 cptr=strtok(NULL, ", :;\t\n\r");
311 n++;
312 }
313 fputs("\n", fp);
314 free(tline);
315 i++; continue;
316 }
317
318
319 /* Print the line one character at the time */
320 len=strlen(line); j=0;
321 while(j<len) {
322
323 /* If WWW Address follows, then add a link */
324 if(strncasecmp(line+j, "https://", 7)==0) {
325 unsigned int li;
326 cptr=line+j; len=strcspn(cptr, " ),;");
327 fputs("<a href=\"", fp);
328 for(li=0; li<len; li++) fputc(line[j+li], fp);
329 fputs("\">", fp);
330 for(li=0; li<len; li++) fputc(line[j+li], fp);
331 fputs("</a>", fp);
332 j+=len; continue;
333 }
334
335 /* If necessary, replace '@P' with program name */
336 if(strncmp(line+j, " @P ", 4)==0) {
337 fprintf(fp, " %s ", bprogram);
338 j+=4; continue;
339 }
340 /* Replace (c) or (C) with html code */
341 if(strncasecmp(line+j, "(C)", 3)==0) {
342 fputs("&copy;", fp);
343 j+=3; continue;
344 }
345
346 /* Replace <, >, and & characters with html codes */
347 if(line[j]=='<') {fputs("&lt;", fp); j++; continue;}
348 if(line[j]=='>') {fputs("&gt;", fp); j++; continue;}
349 if(line[j]=='&') {fputs("&amp;", fp); j++; continue;}
350
351 /* Just write the char normally */
352 fputc(line[j], fp); j++;
353 }
354 fprintf(fp, "\n");
355 i++; continue;
356
357 }
358 fprintf(fp, "</pre>\n");
359
360 /* Write footer */
361 fprintf(fp, "\n<footer>\n");
362 fprintf(fp, "<p>");
363 i=0; while(tpclicense4html[i]!=0) fprintf(fp, "%s<br>\n", tpclicense4html[i++]);
364 fprintf(fp, "</p>\n");
365 fprintf(fp, "</footer>\n");
366
367 /* Close HTML */
368 fprintf(fp, "</body>\n");
369 fprintf(fp, "</html>\n");
370
371
372 free(bprogram); free(fname);
373 return 0;
374}
void filenameRmPath(char *s)
Definition filename.c:13
size_t strnlen(const char *s, size_t n)
Definition strext.c:181

◆ tpcPrintBuild()

void tpcPrintBuild ( const char * program,
FILE * fp )
extern

Print tpctools build information.

Author
Vesa Oikonen
See also
tpcProgramName, tpcPrintUsage
Parameters
programProgram name; enter NULL, if not to be printed.
fpFile pointer where to print; usually stdout.

Definition at line 383 of file proginfo.c.

388 {
389 fprintf(fp, "\n");
390 if(program!=NULL) {
391 /* Print program name */
392 char *s; s=strdup(program);
394 fprintf(fp, " Program: %s\n", s);
395 free(s);
396 }
397 /* Build time */
398 fprintf(fp, " Build: %s %s\n",__DATE__,__TIME__);
399 /* tpcclib (and program) version */
400 fprintf(fp, " tpcclib version: %d.%d.%d\n", tpcclib_VERSION_MAJOR,
401 tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
402 /* Compiler information */
403 fprintf(fp, " Build platform: %s\n", tpcclib_BUILD_HOST_SYSTEM_NAME);
404 fprintf(fp, " Build processor: %s\n", tpcclib_BUILD_HOST_SYSTEM_PROCESSOR);
405#if defined(__STDC_VERSION__)
406 fprintf(fp, " Version of C: %ld\n", __STDC_VERSION__);
407#endif
408#if defined(__GNUC__) && defined(__VERSION__)
409 fprintf(fp, " GNU C version: %s\n", __VERSION__);
410#endif
411#if defined(__clang__) && defined(__clang_version__)
412 fprintf(fp, " Clang/LLVM version: %s\n", __clang_version__);
413#endif
414#ifdef _OPENMP
415 fprintf(fp, " OpenMP version: %d\n", _OPENMP);
416#endif
417 /* Platform information */
418#if defined(__x86_64__) || defined(__LP64__) || defined(__ppc64__) || \
419 defined(__LLP64__) || defined(__ILP64__)
420 fprintf(fp, " Architecture: 64-bit\n");
421#else
422 fprintf(fp, " Architecture: 32-bit\n");
423#endif
424 /* Check if IEC 60559 floating-point standard is officially supported;
425 that is 'always' supported, but PET data i/o functions rely on it.
426 GCC does not define __STDC_IEC_559__ or implement the associated standard pragmas. */
427#ifdef __STDC_IEC_559__
428 fprintf(fp, " IEC 60559 floating-point standard is fully supported.\n");
429#endif
430 /* Large File Support extension (LFS) */
431#if defined(_FILE_OFFSET_BITS)
432 fprintf(fp, " _FILE_OFFSET_BITS: %d\n", _FILE_OFFSET_BITS);
433#else
434 fprintf(fp, " _FILE_OFFSET_BITS not defined\n");
435#endif
436#if defined(_LARGEFILE_SOURCE)
437 fprintf(fp, " _LARGEFILE_SOURCE defined\n");
438#endif
439#if defined(_LARGEFILE64_SOURCE)
440 fprintf(fp, " _LARGEFILE64_SOURCE defined\n");
441#endif
442}

◆ tpcPrintUsage()

void tpcPrintUsage ( const char * program,
char * text[],
FILE * fp )
extern

Print program usage given as argument, plus program name, tpcclib version, and default copyright text.

  • Any string @P, separated by space characters, is replaced by program name in the output. It can only be used once per line.
  • When line contains text 'stdoptions', in place of that the description of standard command-line options '-h, -v, -q, -s etc' are displayed.
    Author
    Vesa Oikonen
    See also
    tpcHtmlUsage, tpcPrintBuild, tpcProcessStdOptions
Parameters
programProgram name
textProgram usage text
fpFile pointer where to print; usually stdout

Definition at line 158 of file proginfo.c.

165 {
166 int i;
167 char *cptr, *bprogram;
168
169 /* Print program name, version, and copyright */
170 if(strlen(program)>0) bprogram=strdup(program);
171 else bprogram=strdup("unknown");
172 filenameRmPath(bprogram); filenameRmExtension(bprogram);
173 fprintf(fp, "\n %s - tpcclib %d.%d.%d %s\n \n", bprogram,
174 tpcclib_VERSION_MAJOR, tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH,
175 tpcclib_COPYRIGHT);
176 /* Print usage */
177 i=0; while(text[i]!=0) {
178 /* If line contains string 'stdoptions' then print instead of it the
179 description of standard command-line options */
180 if(strstr(text[i], "stdoptions")) {
181 int j=0;
182 while(tpcstdoptions[j]!=0) fprintf(fp, " %s\n", tpcstdoptions[j++]);
183 i++; continue;
184 }
185 /* If line does not contain program name, then just print it as it is */
186 cptr=strstr(text[i], " @P ");
187 if(cptr==NULL) {fprintf(fp, " %s\n", text[i++]); continue;}
188 /* Replace '@P' with program name */
189 char *s; s=strdup(text[i]);
190 s[strlen(text[i])-strlen(cptr)]=(char)0;
191 fprintf(fp, " %s %s %s\n", s, bprogram, cptr+4);
192 free(s); i++;
193 }
194 fprintf(fp, " \n");
195 /* Print licence info */
196 i=0; while(tpclicense[i]!=0) fprintf(fp, " %s\n", tpclicense[i++]);
197 fprintf(fp, "\n");
198 free(bprogram);
199}

◆ tpcProcessStdOptions()

int tpcProcessStdOptions ( const char * s,
int * print_usage,
int * print_version,
int * verbose_level )
extern

Check if given command-line argument string is one of the standard command-line options of this project.

Returns
0 if string was identified as standard option, otherwise 1.
Author
Vesa Oikonen
See also
tpcProgramName, tpcPrintUsage
Parameters
sPointer to command-line option string.
print_usageIf option string is either -h or –help, then this variable is set to 1.
print_versionIf option string is either -v, -V, –version, or –build, then this variable is set to 1.
verbose_levelThe level of debugging messages and listings:
  • If option string is -d, –debug or –verbose, then +1 is added to this variable.
  • If option string is -d[n], –debug[=n], or –verbose[=n], then +n is added to this variable.
  • If options string is -q or –quiet, then this variable is set to 0.
  • If options string is -s or –silent, then this variable is set to -1.

Definition at line 40 of file proginfo.c.

54 {
55 int n;
56
57 char *cptr;
58 /* Check that string is option, starting with '-' or '--' */
59 if(s==NULL || strlen(s)<2 || s[0]!='-') return 1;
60 /* Set pointer to the character after the first '-' */
61 cptr=(char*)s+1;
62 /* If also the next character is '-', then try the long forms of options */
63 if(*cptr=='-') {
64 cptr++; if(strlen(cptr)<1) return 1;
65 if(strcasecmp(cptr, "help")==0) {*print_usage=1; return 0;}
66 if(strcasecmp(cptr, "helphtml")==0) {*print_usage=2; return 0;}
67 if(strcasecmp(cptr, "version")==0) {*print_version=1; return 0;}
68 if(strcasecmp(cptr, "build")==0) {*print_version=1; return 0;}
69 if(strcasecmp(cptr, "debug")==0) {*verbose_level+=1; return 0;}
70 if(strcasecmp(cptr, "verbose")==0) {*verbose_level+=1; return 0;}
71 if(strncasecmp(cptr, "debug=", 6)==0) {
72 if(!isdigit(cptr[6])) return 1;
73 n=atoi(cptr+6); *verbose_level+=n; return 0;
74 }
75 if(strncasecmp(cptr, "verbose=", 8)==0) {
76 if(!isdigit(cptr[8])) return 1;
77 n=atoi(cptr+8); *verbose_level+=n; return 0;
78 }
79 if(strcasecmp(cptr, "quiet")==0) {*verbose_level=0; return 0;}
80 if(strcasecmp(cptr, "silent")==0) {*verbose_level=-1; return 0;}
81 return 1;
82 }
83 /* So it is the short form, if anything */
84 if(strcmp(cptr, "h")==0) {*print_usage=1; return 0;}
85 if(strcasecmp(cptr, "v")==0) {*print_version=1; return 0;}
86 if(strcmp(cptr, "d")==0) {*verbose_level+=1; return 0;}
87 if(strncmp(cptr, "d", 1)==0 && strlen(cptr)>1) {
88 if(!isdigit(cptr[1])) return 1;
89 n=atoi(cptr+1); *verbose_level+=n; return 0;
90 }
91 if(strcmp(cptr, "q")==0) {*verbose_level=0; return 0;}
92 if(strcmp(cptr, "s")==0) {*verbose_level=-1; return 0;}
93 return 1;
94}

◆ tpcProgramName()

void tpcProgramName ( const char * program,
int version,
int copyright,
char * prname,
int n )
extern

Process program name and optionally version into given string from argv[0].

See also
tpcPrintBuild, tpcPrintUsage, tpcProcessStdOptions
Parameters
programSet to argv[0]
versionAdd version (1) or do not add (0)
copyrightAdd copyright (1) or do not add (0)
prnamePointer to string where program name is written
nLength of prname string, including trailing zero

Definition at line 101 of file proginfo.c.

112 {
113 char *tmp;
114
115 /* Check the input */
116 if(prname==NULL || n<1) return;
117 prname[0]=(char)0;
118
119 /* Remove path and extension */
120 if(strlen(program)>0) tmp=strdup(program); else tmp=strdup("unknown");
122 /* Copy it if possible */
123 n-=strlen(tmp); if(n>0) strcpy(prname, tmp); else {free(tmp); return;}
124 free(tmp);
125
126 /* Add version, if required */
127 if(version!=0) {
128 /* Create string with version number */
129 char v[256];
130 sprintf(v, "%d.%d.%d", tpcclib_VERSION_MAJOR, tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
131 /* Copy it if possible */
132 n--; // space
133 n-=strlen(v); if(n>0) {strcat(prname, " "); strcat(prname, v);}
134 }
135
136 /* Add copyright, if required */
137 if(copyright!=0) {
138 /* Copy it if possible */
139 n--; // space
140 n-=strlen(tpcclib_COPYRIGHT);
141 if(n>0) {strcat(prname, " "); strcat(prname, tpcclib_COPYRIGHT);}
142 }
143
144 return;
145}