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

Header file for library libtpcextensions. More...

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

Go to the source code of this file.

Data Structures

struct  TPCSTATUS
 
struct  INTLIST
 

Macros

#define MAX_UNITS_LEN   32
 Define max units string length.
 
#define MAX_TACNAME_LEN   31
 Max length of TAC ID name (not including trailing zero)
 
#define MAX_PARNAME_LEN   MAX_TACNAME_LEN
 Max string length for PAR name.
 
#define MAX_STUDYNR_LEN   255
 Define max study number length.
 

Enumerations

enum  weights {
  WEIGHTING_UNKNOWN , WEIGHTING_OFF , WEIGHTING_ON_GENERAL , WEIGHTING_ON_COUNTS ,
  WEIGHTING_ON_F , WEIGHTING_ON_FD , WEIGHTING_LAST
}
 Is data weighted, or are weight factors available with data? More...
 
enum  tactype {
  TACTYPE_UNKNOWN , TACTYPE_PLASMA , TACTYPE_BLOOD , TACTYPE_PARENT ,
  TACTYPE_METABOLITE , TACTYPE_VOI , TACTYPE_REF , TACTYPE_PIXEL ,
  TACTYPE_LAST
}
 TAC content types. More...
 
enum  unit {
  UNIT_UNKNOWN , UNIT_UNITLESS , UNIT_HU , UNIT_MSEC ,
  UNIT_SEC , UNIT_MIN , UNIT_HOUR , UNIT_DAY ,
  UNIT_MONTH , UNIT_YEAR , UNIT_UM , UNIT_MM ,
  UNIT_CM , UNIT_M , UNIT_UL , UNIT_ML ,
  UNIT_DL , UNIT_L , UNIT_UG , UNIT_MG ,
  UNIT_G , UNIT_100G , UNIT_KG , UNIT_PMOL ,
  UNIT_NMOL , UNIT_UMOL , UNIT_MMOL , UNIT_MOL ,
  UNIT_COUNTS , UNIT_KCOUNTS , UNIT_BQ , UNIT_KBQ ,
  UNIT_MBQ , UNIT_GBQ , UNIT_NCI , UNIT_UCI ,
  UNIT_MCI , UNIT_CI , UNIT_CPS , UNIT_KCPS ,
  UNIT_CPM , UNIT_KCPM , UNIT_BQ_PER_ML , UNIT_KBQ_PER_ML ,
  UNIT_MBQ_PER_ML , UNIT_NCI_PER_ML , UNIT_UCI_PER_ML , UNIT_BQ_PER_G ,
  UNIT_KBQ_PER_G , UNIT_MBQ_PER_G , UNIT_NCI_PER_G , UNIT_UCI_PER_G ,
  UNIT_PMOL_PER_ML , UNIT_NMOL_PER_ML , UNIT_UMOL_PER_ML , UNIT_MMOL_PER_ML ,
  UNIT_PMOL_PER_L , UNIT_NMOL_PER_L , UNIT_UMOL_PER_L , UNIT_MMOL_PER_L ,
  UNIT_MOL_PER_L , UNIT_SEC_KBQ_PER_ML , UNIT_MIN_KBQ_PER_ML , UNIT_SEC_BQ_PER_ML ,
  UNIT_MIN_BQ_PER_ML , UNIT_PERCENTAGE , UNIT_ML_PER_ML , UNIT_ML_PER_DL ,
  UNIT_G_PER_ML , UNIT_ML_PER_G , UNIT_PER_SEC , UNIT_PER_MIN ,
  UNIT_PER_HOUR , UNIT_ML_PER_ML_SEC , UNIT_ML_PER_ML_MIN , UNIT_ML_PER_DL_MIN ,
  UNIT_ML_PER_G_MIN , UNIT_ML_PER_100G_MIN , UNIT_UMOL_PER_ML_MIN , UNIT_UMOL_PER_DL_MIN ,
  UNIT_UMOL_PER_G_MIN , UNIT_UMOL_PER_100G_MIN , UNIT_MMOL_PER_ML_MIN , UNIT_MMOL_PER_DL_MIN ,
  UNIT_MMOL_PER_G_MIN , UNIT_MMOL_PER_100G_MIN , UNIT_MG_PER_100G_MIN , UNIT_MG_PER_DL_MIN ,
  UNIT_PID , UNIT_PID_PER_G , UNIT_PID_PER_ML , UNIT_PID_PER_KG ,
  UNIT_PID_PER_L , UNIT_MBQ_PER_NMOL , UNIT_GBQ_PER_NMOL , UNIT_LAST
}
 
enum  tpcerror {
  TPCERROR_OK , TPCERROR_FAIL , TPCERROR_OUT_OF_MEMORY , TPCERROR_NO_FILE ,
  TPCERROR_FILE_EXISTS , TPCERROR_INVALID_FILENAME , TPCERROR_CANNOT_OPEN , TPCERROR_CANNOT_READ ,
  TPCERROR_CANNOT_WRITE , TPCERROR_CANNOT_DELETE , TPCERROR_INVALID_FORMAT , TPCERROR_UNSUPPORTED ,
  TPCERROR_NO_DATA , TPCERROR_DUPLICATE_DATA , TPCERROR_NO_WEIGHTS , TPCERROR_NO_DATETIME ,
  TPCERROR_MISSING_DATA , TPCERROR_TOO_FEW , TPCERROR_TOO_BIG , TPCERROR_OVERLAPPING_DATA ,
  TPCERROR_LARGE_GAP , TPCERROR_NO_X , TPCERROR_INVALID_X , TPCERROR_INVALID_XRANGE ,
  TPCERROR_INCOMPATIBLE_UNIT , TPCERROR_INCOMPATIBLE_DATA , TPCERROR_NO_REFERENCE , TPCERROR_NO_KEY ,
  TPCERROR_NO_VALUE , TPCERROR_INVALID_VALUE , TPCERROR_INVALID_SEPARATOR , TPCERROR_INVALID_PARNR ,
  TPCERROR_INVALID_HEADER , TPCERROR_MISSING_HEADER , TPCERROR_UNKNOWN_ISOTOPE , TPCERROR_UNKNOWN_UNIT ,
  TPCERROR_NO_SOLUTION , TPCERROR_BAD_FIT , TPCERROR_LAST
}
 Error codes. Error code tpcerror, same as error message position in the table (table can not be accessed directly outside the c file). More...
 
enum  {
  ENDIAN_UNKNOWN , ENDIAN_BIG , ENDIAN_LITTLE , ENDIAN_BIG_WORD ,
  ENDIAN_LITTLE_WORD
}
 

Functions

int strTokenNr (const char *s1, const char *s2)
 
int strTokenNCpy (const char *s1, const char *s2, int i, char *s3, int count)
 
int strChrCount (const char *s1, const char *s2)
 
int strUppercaseCount (const char *s)
 
void strReplaceChar (char *s, char c1, char c2)
 
char * strcasestr (const char *haystack, const char *needle)
 
char * strdup (const char *s)
 
char * strndup (const char *s, size_t n)
 
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 * strstrNoQuotation (const char *haystack, const char *needle)
 
int strncpyCleanSpaces (char *s1, const char *s2, int maxlen)
 
int strCleanSpaces (char *s)
 
int strncpyClean (char *s1, const char *s2, int maxlen)
 
int strClean (char *s)
 
char * strTokenDup (const char *s1, const char *s2, int *next)
 
int strInPars (char *s)
 
void strCleanPars (char *s)
 
char * strncatInt (char *str1, const int n, size_t count)
 
char * strncatDouble (char *str1, const double d, size_t count)
 
char * strncatIntZ (char *str1, const int n, const int maxn, size_t count)
 
int strIsSpaceOnly (char *s)
 
char * strdelstr (char *s1, const char *s2)
 
char * strTrimLeft (char *s, const size_t t)
 
char * strEncodeForXML (const char *s)
 
void strCleanForXML (char *s)
 
int strIsValidNumber (const char *s)
 
double atofVerified (const char *s)
 
int atofCheck (const char *s, double *v)
 
int strHaveDecimalComma (const char *s)
 
int strHaveDecimalSeparator (const char *s)
 
int atofList (const char *s1, const char *s2, double *x, int maxn)
 
void filenameRmPath (char *s)
 
void filenameRmFile (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 (const char *s)
 Get the last extension of a file name.
 
char * filenameGetExtensions (const char *s)
 Get all extensions of a file name.
 
int tpcProcessStdOptions (const char *s, int *print_usage, int *print_version, int *verbose_level)
 
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)
 
void tpcProgramName (const char *program, int version, int copyright, char *prname, int n)
 
int tpcYesNo (const char *s)
 
char * unitName (int unit_code)
 
int unitIdentify (const char *s)
 
int unitIdentifyFilename (const char *s)
 
int unitIsDistance (int u)
 
int unitIsTime (int u)
 
int unitIsVolume (int u)
 
int unitIsMass (int u)
 
int unitIsMole (int u)
 
int unitIsRadioactivity (int u)
 
int unitIsRAConc (int u)
 
int unitIsCombinatorial (int u)
 
double unitConversionFactor (const int u1, const int u2)
 
int unitInverse (int u)
 
int unitDividerHasVolume (int u)
 
int unitDividerHasMass (int u)
 
int unitDividendHasRadioactivity (int u)
 
int unitCombination (const int u1, const int u2, const int v1, const int v2)
 
int unitDividerMassVolumeConversion (int u)
 
int unitMultiply (int ua, int ub)
 
void statusPrint (FILE *fp, TPCSTATUS *s)
 
void statusInit (TPCSTATUS *s)
 
void statusFree (TPCSTATUS *s)
 
void statusSet (TPCSTATUS *s, const char *func, const char *srcfile, int srcline, tpcerror error)
 
char * errorMsg (tpcerror e)
 
size_t asciiFileSize (FILE *fp, int *nonprintable)
 
char * asciiFileRead (FILE *fp, char *data, size_t maxlen)
 
int asciiCommentLine (const char *line, int *cont)
 
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 calendar 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 strDateValid (const char *str)
 
int strDateValid2 (const char *str, char *intdate)
 
int strDateValid3 (const char *str, char *intdate)
 
int strDateValid4 (int dateint, char *intdate, int *year, int *month, int *day)
 
int strTimeValid (const char *str)
 
int strDateTimeValid (const char *str, char *intdate)
 
int strDateTimeRead (const char *str, struct tm *date)
 
int strDateRead (const char *str, struct tm *date)
 
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)
 
double strDateTimeDifference (const char *dt1, const char *dt0)
 
int strDateTimeAdd (int s, char *dt)
 
int studynrVerify (const char *s, int zero_ok)
 
int studynrStandardize (char *s)
 
int studynrFromFilename (const char *fname, char *studynr, int force)
 
int doubleMatch (const double v1, const double v2, const double lim)
 
int doubleArrayMatch (const double *a1, const double *a2, const unsigned int n, 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 doubleCopyFinite (double *t, double *s, const unsigned int n)
 
unsigned int doubleNaNs (double *a, const unsigned int n)
 
unsigned int doubleRange (double *a, const unsigned int n, double *amin, double *amax)
 
double doubleSum (double *a, const unsigned int n)
 
double doubleMean (double *a, const unsigned int n)
 
double doubleWMean (double *a, double *w, const unsigned int n)
 
int doubleGetWithUnit (const char *s, double *v, int *u)
 
int doubleSpanPositives (double *a, const int n)
 
int doubleCSpanPositives (double *a, const int n)
 
unsigned int doubleNonzeroes (double *a, const unsigned int n)
 
unsigned int doubleMaxIndex (double *a, const unsigned int n)
 
unsigned int doubleAbsMaxIndex (double *a, const unsigned int n)
 
unsigned int doubleMinIndex (double *a, const unsigned int n)
 
unsigned int doubleAbsMinIndex (double *a, const unsigned int n)
 
unsigned int doubleGEIndex (double *a, const unsigned int n, double lim)
 
unsigned int doubleGTIndex (double *a, const unsigned int n, double lim)
 
double inverfc (double x)
 
int floatMatch (const float v1, const float v2, const float lim)
 
int floatMatchRel (const float v1, const float v2, const float lim)
 
float floatMachEps ()
 
void floatCopy (float *t, float *s, const unsigned int n)
 
unsigned int floatMaxIndex (float *a, const unsigned int n)
 
float floatSum (float *a, const unsigned int n)
 
float floatMean (float *a, const unsigned int n)
 
int floatGetWithUnit (const char *s, float *v, int *u)
 
int floatSpanPositives (float *a, const int n)
 
int floatCSpanPositives (float *a, const int n)
 
unsigned int floatNonzeroes (float *a, const unsigned int n)
 
int atoiCheck (const char *s, int *v)
 
unsigned int factorial (unsigned int n)
 
unsigned long long int lfactorial (unsigned long long int n)
 
void intlistInit (INTLIST *l)
 
void intlistFree (INTLIST *l)
 
int intlistAdd (INTLIST *l, const int v, const int ifnew)
 
void intlistSort (INTLIST *l)
 
int intlistAddFromString (const char *s1, const char *s2, INTLIST *l, const int ifnew)
 
int intlistExpandFromString (const char *s1, const char *s2, INTLIST *l, const int ifnew)
 
char * roinameSubpart (const char *roiname, const char *dlm, const unsigned int si, char *subpart, const unsigned int slen)
 
char * roinameEditByTemplate (const char *template, const char *currname, char *newname, const unsigned int count)
 
char * roinameAddField (char *roiname, const char *field, const unsigned int in, const unsigned int count)
 
int roinameExists (char *roiname)
 Verifies whether TAC name exists or not.
 
int roinameMatch (const char *roiname, const char *test_str, TPCSTATUS *status)
 
int endianness ()
 
int endianLittle ()
 
void swap (void *from, void *to, int size)
 
void swabip (void *buf, int size)
 
void swawbip (void *buf, int size)
 
void swawip (void *buf, int size)
 
void swap64ip (void *buf, unsigned long long size)
 
void swap32ip (void *buf, unsigned long long size)
 
void swap16ip (void *buf, unsigned long long size)
 

Detailed Description

Header file for library libtpcextensions.

Author
Vesa Oikonen

Definition in file tpcextensions.h.

Macro Definition Documentation

◆ MAX_PARNAME_LEN

#define MAX_PARNAME_LEN   MAX_TACNAME_LEN

Max string length for PAR name.

Max length of parameter names and units

Definition at line 39 of file tpcextensions.h.

Referenced by parEnsureNames(), parFromIFT(), parReadCSV(), parReadLimits(), parReadRES(), parWriteCSV(), and parWriteLimits().

◆ MAX_STUDYNR_LEN

#define MAX_STUDYNR_LEN   255

Define max study number length.

Max string length for PET study number

Definition at line 46 of file tpcextensions.h.

Referenced by imgCopyHeader(), imgInit(), imgReadDICOM(), tacGetHeaderStudynr(), tacRead(), tacReadSIF(), and tacWriteSIF().

◆ MAX_TACNAME_LEN

#define MAX_TACNAME_LEN   31

Max length of TAC ID name (not including trailing zero)

Max string length for TAC name

Definition at line 35 of file tpcextensions.h.

Referenced by parEnsureNames(), parFromIFT(), parReadCSV(), parReadFIT(), parReadRES(), tacEnsureNames(), tacRead4DM(), tacReadCarimasTxt(), tacReadCSV(), tacReadDFT(), tacReadInveonCSV(), tacReadMat(), tacReadPMOD(), tacReadQView(), and tacReadSimple().

◆ MAX_UNITS_LEN

#define MAX_UNITS_LEN   32

Define max units string length.

Max string length for PET units

Definition at line 28 of file tpcextensions.h.

Referenced by parWriteCSV().

Enumeration Type Documentation

◆ anonymous enum

anonymous enum

Definition at line 488 of file tpcextensions.h.

488 { // used by endianness()
489 ENDIAN_UNKNOWN,
490 ENDIAN_BIG,
491 ENDIAN_LITTLE,
492 ENDIAN_BIG_WORD, /* Middle-endian, Honeywell 316 style */
493 ENDIAN_LITTLE_WORD /* Middle-endian, PDP-11 style */
494};

◆ tactype

enum tactype

TAC content types.

Enumerator
TACTYPE_UNKNOWN 

Content type not known.

TACTYPE_PLASMA 

Plasma TAC.

TACTYPE_BLOOD 

Blood TAC.

TACTYPE_PARENT 

Parent tracer in plasma.

TACTYPE_METABOLITE 

Metabolite in plasma.

TACTYPE_VOI 

Image volume-of-interest TAC.

TACTYPE_REF 

Reference region TAC.

TACTYPE_PIXEL 

Image pixel TAC.

Definition at line 66 of file tpcextensions.h.

66 {
75 TACTYPE_LAST
76} tactype;
tactype
TAC content types.
@ TACTYPE_REF
Reference region TAC.
@ TACTYPE_PARENT
Parent tracer in plasma.
@ TACTYPE_UNKNOWN
Content type not known.
@ TACTYPE_METABOLITE
Metabolite in plasma.
@ TACTYPE_PLASMA
Plasma TAC.
@ TACTYPE_PIXEL
Image pixel TAC.
@ TACTYPE_VOI
Image volume-of-interest TAC.
@ TACTYPE_BLOOD
Blood TAC.

◆ tpcerror

enum tpcerror

Error codes. Error code tpcerror, same as error message position in the table (table can not be accessed directly outside the c file).

See also
tpcerrormsg, statusmsg.c, TPCSTATUS
Enumerator
TPCERROR_OK 

No error.

TPCERROR_FAIL 

General error.

TPCERROR_OUT_OF_MEMORY 

Cannot allocate memory.

TPCERROR_NO_FILE 

File does not exist.

TPCERROR_FILE_EXISTS 

File exists.

TPCERROR_INVALID_FILENAME 

Invalid file name.

TPCERROR_CANNOT_OPEN 

Cannot open file.

TPCERROR_CANNOT_READ 

Cannot read file.

TPCERROR_CANNOT_WRITE 

Cannot write file.

TPCERROR_CANNOT_DELETE 

Cannot delete.

TPCERROR_INVALID_FORMAT 

Invalid file format.

TPCERROR_UNSUPPORTED 

Unsupported file type.

TPCERROR_NO_DATA 

File contains no data.

TPCERROR_DUPLICATE_DATA 

File contains duplicate data.

TPCERROR_NO_WEIGHTS 

File contains no weights.

TPCERROR_NO_DATETIME 

File contains no date or time.

TPCERROR_MISSING_DATA 

File contains missing values.

TPCERROR_TOO_FEW 

File contains too few samples.

TPCERROR_TOO_BIG 

File is too big.

TPCERROR_OVERLAPPING_DATA 

Overlapping data.

TPCERROR_LARGE_GAP 

Large gap in data.

TPCERROR_NO_X 

No sample times.

TPCERROR_INVALID_X 

Invalid sample time.

TPCERROR_INVALID_XRANGE 

Invalid sample time range.

TPCERROR_INCOMPATIBLE_UNIT 

Incompatible units.

TPCERROR_INCOMPATIBLE_DATA 

Incompatible data.

TPCERROR_NO_REFERENCE 

Reference not found.

TPCERROR_NO_KEY 

Key not found.

TPCERROR_NO_VALUE 

Value not found.

TPCERROR_INVALID_VALUE 

Invalid value.

TPCERROR_INVALID_SEPARATOR 

Invalid field delimiter.

TPCERROR_INVALID_PARNR 

Invalid number of parameters.

TPCERROR_INVALID_HEADER 

Invalid header contents.

TPCERROR_MISSING_HEADER 

Missing header.

TPCERROR_UNKNOWN_ISOTOPE 

Unknown isotope.

TPCERROR_UNKNOWN_UNIT 

Unknown data unit.

TPCERROR_NO_SOLUTION 

No solution.

TPCERROR_BAD_FIT 

Fitting not successful.

TPCERROR_LAST 

marking the end of list

Definition at line 189 of file tpcextensions.h.

189 {
190// tpcerrormsg[] in statusmsg.c must be edited accordingly
230} tpcerror;
tpcerror
Error codes. Error code tpcerror, same as error message position in the table (table can not be acces...
@ TPCERROR_NO_REFERENCE
Reference not found.
@ TPCERROR_INVALID_SEPARATOR
Invalid field delimiter.
@ TPCERROR_DUPLICATE_DATA
File contains duplicate data.
@ TPCERROR_INVALID_XRANGE
Invalid sample time range.
@ TPCERROR_INVALID_VALUE
Invalid value.
@ TPCERROR_NO_FILE
File does not exist.
@ TPCERROR_NO_SOLUTION
No solution.
@ TPCERROR_INVALID_PARNR
Invalid number of parameters.
@ TPCERROR_NO_VALUE
Value not found.
@ TPCERROR_OVERLAPPING_DATA
Overlapping data.
@ TPCERROR_NO_DATETIME
File contains no date or time.
@ TPCERROR_BAD_FIT
Fitting not successful.
@ TPCERROR_UNKNOWN_UNIT
Unknown data unit.
@ TPCERROR_FAIL
General error.
@ TPCERROR_INVALID_FORMAT
Invalid file format.
@ TPCERROR_INVALID_HEADER
Invalid header contents.
@ TPCERROR_TOO_BIG
File is too big.
@ TPCERROR_CANNOT_OPEN
Cannot open file.
@ TPCERROR_OUT_OF_MEMORY
Cannot allocate memory.
@ TPCERROR_INVALID_X
Invalid sample time.
@ TPCERROR_NO_KEY
Key not found.
@ TPCERROR_NO_X
No sample times.
@ TPCERROR_UNSUPPORTED
Unsupported file type.
@ TPCERROR_FILE_EXISTS
File exists.
@ TPCERROR_OK
No error.
@ TPCERROR_LAST
marking the end of list
@ TPCERROR_NO_WEIGHTS
File contains no weights.
@ TPCERROR_INCOMPATIBLE_UNIT
Incompatible units.
@ TPCERROR_LARGE_GAP
Large gap in data.
@ TPCERROR_INVALID_FILENAME
Invalid file name.
@ TPCERROR_UNKNOWN_ISOTOPE
Unknown isotope.
@ TPCERROR_NO_DATA
File contains no data.
@ TPCERROR_MISSING_HEADER
Missing header.
@ TPCERROR_CANNOT_DELETE
Cannot delete.
@ TPCERROR_TOO_FEW
File contains too few samples.
@ TPCERROR_CANNOT_READ
Cannot read file.
@ TPCERROR_MISSING_DATA
File contains missing values.
@ TPCERROR_INCOMPATIBLE_DATA
Incompatible data.
@ TPCERROR_CANNOT_WRITE
Cannot write file.

◆ unit

enum unit

unit code, same as unit position in the table (table can not be accessed directly outside the c file).

See also
units.c unitName, unitIdentify, unitConversionFactor
Enumerator
UNIT_UNKNOWN 

Unknown unit.

UNIT_UNITLESS 

Unitless.

UNIT_HU 

Hounsfield Unit.

UNIT_MSEC 

milliseconds

UNIT_SEC 

seconds

UNIT_MIN 

minutes

UNIT_HOUR 

hours

UNIT_DAY 

days

UNIT_MONTH 

months

UNIT_YEAR 

years

UNIT_UM 

micrometer

UNIT_MM 

millimeter

UNIT_CM 

centimeter

UNIT_M 

meter

UNIT_UL 

microliter

UNIT_ML 

milliliter

UNIT_DL 

desiliter

UNIT_L 

liter

UNIT_UG 

microgram

UNIT_MG 

milligram

UNIT_G 

gram

UNIT_100G 

100 grams

UNIT_KG 

kilogram

UNIT_PMOL 

picomole

UNIT_NMOL 

nanomole

UNIT_UMOL 

micromole

UNIT_MMOL 

millimole

UNIT_MOL 

mole

UNIT_COUNTS 

counts

UNIT_KCOUNTS 

kilocounts

UNIT_BQ 

Becquerel.

UNIT_KBQ 

kiloBecquerel

UNIT_MBQ 

megaBecquerel

UNIT_GBQ 

gigaBecquerel

UNIT_NCI 

nanoCurie

UNIT_UCI 

microCurie

UNIT_MCI 

milliCurie

UNIT_CI 

Curie.

UNIT_CPS 

counts/s

UNIT_KCPS 

kilocounts/s

UNIT_CPM 

counts/min

UNIT_KCPM 

kilocounts/min

UNIT_BQ_PER_ML 

Bq/mL.

UNIT_KBQ_PER_ML 

kBq/mL

UNIT_MBQ_PER_ML 

MBq/mL.

UNIT_NCI_PER_ML 

nCi/mL

UNIT_UCI_PER_ML 

uCi/mL

UNIT_BQ_PER_G 

Bq/g.

UNIT_KBQ_PER_G 

kBq/g

UNIT_MBQ_PER_G 

MBq/g.

UNIT_NCI_PER_G 

nCi/g

UNIT_UCI_PER_G 

uCi/g

UNIT_PMOL_PER_ML 

pmol/mL

UNIT_NMOL_PER_ML 

nmol/mL

UNIT_UMOL_PER_ML 

umol/mL

UNIT_MMOL_PER_ML 

mmol/mL

UNIT_PMOL_PER_L 

pmol/L

UNIT_NMOL_PER_L 

nmol/L

UNIT_UMOL_PER_L 

umol/L

UNIT_MMOL_PER_L 

mmol/L

UNIT_MOL_PER_L 

mol/L

UNIT_SEC_KBQ_PER_ML 

s*kBq/mL

UNIT_MIN_KBQ_PER_ML 

min*kBq/mL

UNIT_SEC_BQ_PER_ML 

s*Bq/mL

UNIT_MIN_BQ_PER_ML 

min*Bq/mL

UNIT_PERCENTAGE 

Percentage (%)

UNIT_ML_PER_ML 

mL/mL

UNIT_ML_PER_DL 

mL/dL

UNIT_G_PER_ML 

g/mL

UNIT_ML_PER_G 

mL/g

UNIT_PER_SEC 

1/s

UNIT_PER_MIN 

1/min

UNIT_PER_HOUR 

1/h

UNIT_ML_PER_ML_SEC 

mL/(mL*sec)

UNIT_ML_PER_ML_MIN 

mL/(mL*min)

UNIT_ML_PER_DL_MIN 

mL/(dL*min)

UNIT_ML_PER_G_MIN 

mL/(g*min)

UNIT_ML_PER_100G_MIN 

mL/(100g*min)

UNIT_UMOL_PER_ML_MIN 

umol/(mL*min)

UNIT_UMOL_PER_DL_MIN 

umol/(dL*min)

UNIT_UMOL_PER_G_MIN 

umol/(g*min)

UNIT_UMOL_PER_100G_MIN 

umol/(100g*min)

UNIT_MMOL_PER_ML_MIN 

mmol/(mL*min)

UNIT_MMOL_PER_DL_MIN 

mmol/(dL*min)

UNIT_MMOL_PER_G_MIN 

mmol/(g*min)

UNIT_MMOL_PER_100G_MIN 

mmol/(100g*min)

UNIT_MG_PER_100G_MIN 

mg/(100g*min)

UNIT_MG_PER_DL_MIN 

mg/(dL*min)

UNIT_PID 

Percent of injected dose.

UNIT_PID_PER_G 

Percent of injected dose / g.

UNIT_PID_PER_ML 

Percent of injected dose / mL.

UNIT_PID_PER_KG 

Percent of injected dose / kg.

UNIT_PID_PER_L 

Percent of injected dose / L.

UNIT_MBQ_PER_NMOL 

MBq/nmol (specific activity)

UNIT_GBQ_PER_NMOL 

GBq/nmol (specific activity)

UNIT_LAST 

end of list

Definition at line 84 of file tpcextensions.h.

84 {
87 UNIT_HU,
88 UNIT_MSEC,
89 UNIT_SEC,
90 UNIT_MIN,
91 UNIT_HOUR,
92 UNIT_DAY,
94 UNIT_YEAR,
95 UNIT_UM,
96 UNIT_MM,
97 UNIT_CM,
98 UNIT_M,
99 UNIT_UL,
100 UNIT_ML,
101 UNIT_DL,
102 UNIT_L,
103 UNIT_UG,
104 UNIT_MG,
105 UNIT_G,
106 UNIT_100G,
107 UNIT_KG,
108 UNIT_PMOL,
109 UNIT_NMOL,
110 UNIT_UMOL,
111 UNIT_MMOL,
112 UNIT_MOL,
115 UNIT_BQ,
116 UNIT_KBQ,
117 UNIT_MBQ,
118 UNIT_GBQ,
119 UNIT_NCI,
120 UNIT_UCI,
121 UNIT_MCI,
122 UNIT_CI,
123 UNIT_CPS,
124 UNIT_KCPS,
125 UNIT_CPM,
126 UNIT_KCPM,
173 UNIT_PID,
180 UNIT_LAST
181} unit;
unit
@ UNIT_UMOL_PER_DL_MIN
umol/(dL*min)
@ UNIT_L
liter
@ UNIT_MMOL_PER_DL_MIN
mmol/(dL*min)
@ UNIT_MIN_KBQ_PER_ML
min*kBq/mL
@ UNIT_YEAR
years
@ UNIT_MMOL_PER_G_MIN
mmol/(g*min)
@ UNIT_MOL
mole
@ UNIT_BQ_PER_G
Bq/g.
@ UNIT_MBQ_PER_ML
MBq/mL.
@ UNIT_MIN
minutes
@ UNIT_KG
kilogram
@ UNIT_ML_PER_ML
mL/mL
@ UNIT_MMOL_PER_100G_MIN
mmol/(100g*min)
@ UNIT_ML_PER_ML_MIN
mL/(mL*min)
@ UNIT_MSEC
milliseconds
@ UNIT_UMOL_PER_ML_MIN
umol/(mL*min)
@ UNIT_MIN_BQ_PER_ML
min*Bq/mL
@ UNIT_CPS
counts/s
@ UNIT_MG_PER_DL_MIN
mg/(dL*min)
@ UNIT_PID_PER_L
Percent of injected dose / L.
@ UNIT_UMOL
micromole
@ UNIT_MBQ
megaBecquerel
@ UNIT_UNKNOWN
Unknown unit.
@ UNIT_ML_PER_100G_MIN
mL/(100g*min)
@ UNIT_CPM
counts/min
@ UNIT_KCOUNTS
kilocounts
@ UNIT_UMOL_PER_L
umol/L
@ UNIT_ML
milliliter
@ UNIT_PER_SEC
1/s
@ UNIT_KCPM
kilocounts/min
@ UNIT_ML_PER_DL
mL/dL
@ UNIT_KCPS
kilocounts/s
@ UNIT_MMOL_PER_ML
mmol/mL
@ UNIT_MOL_PER_L
mol/L
@ UNIT_G
gram
@ UNIT_PID_PER_G
Percent of injected dose / g.
@ UNIT_NMOL
nanomole
@ UNIT_UCI_PER_G
uCi/g
@ UNIT_KBQ
kiloBecquerel
@ UNIT_LAST
end of list
@ UNIT_ML_PER_G
mL/g
@ UNIT_NMOL_PER_ML
nmol/mL
@ UNIT_SEC_BQ_PER_ML
s*Bq/mL
@ UNIT_KBQ_PER_ML
kBq/mL
@ UNIT_MONTH
months
@ UNIT_ML_PER_G_MIN
mL/(g*min)
@ UNIT_ML_PER_DL_MIN
mL/(dL*min)
@ UNIT_UNITLESS
Unitless.
@ UNIT_PMOL_PER_L
pmol/L
@ UNIT_G_PER_ML
g/mL
@ UNIT_PID_PER_ML
Percent of injected dose / mL.
@ UNIT_MMOL_PER_ML_MIN
mmol/(mL*min)
@ UNIT_CM
centimeter
@ UNIT_UCI_PER_ML
uCi/mL
@ UNIT_COUNTS
counts
@ UNIT_DL
desiliter
@ UNIT_MBQ_PER_NMOL
MBq/nmol (specific activity)
@ UNIT_MCI
milliCurie
@ UNIT_NMOL_PER_L
nmol/L
@ UNIT_PER_HOUR
1/h
@ UNIT_SEC
seconds
@ UNIT_MBQ_PER_G
MBq/g.
@ UNIT_NCI
nanoCurie
@ UNIT_KBQ_PER_G
kBq/g
@ UNIT_DAY
days
@ UNIT_PID
Percent of injected dose.
@ UNIT_100G
100 grams
@ UNIT_UMOL_PER_ML
umol/mL
@ UNIT_PID_PER_KG
Percent of injected dose / kg.
@ UNIT_GBQ_PER_NMOL
GBq/nmol (specific activity)
@ UNIT_ML_PER_ML_SEC
mL/(mL*sec)
@ UNIT_UG
microgram
@ UNIT_MM
millimeter
@ UNIT_BQ
Becquerel.
@ UNIT_UMOL_PER_G_MIN
umol/(g*min)
@ UNIT_SEC_KBQ_PER_ML
s*kBq/mL
@ UNIT_PMOL_PER_ML
pmol/mL
@ UNIT_PMOL
picomole
@ UNIT_HU
Hounsfield Unit.
@ UNIT_UL
microliter
@ UNIT_HOUR
hours
@ UNIT_UMOL_PER_100G_MIN
umol/(100g*min)
@ UNIT_UM
micrometer
@ UNIT_UCI
microCurie
@ UNIT_MMOL_PER_L
mmol/L
@ UNIT_PER_MIN
1/min
@ UNIT_GBQ
gigaBecquerel
@ UNIT_PERCENTAGE
Percentage (%)
@ UNIT_CI
Curie.
@ UNIT_NCI_PER_G
nCi/g
@ UNIT_MG
milligram
@ UNIT_BQ_PER_ML
Bq/mL.
@ UNIT_MG_PER_100G_MIN
mg/(100g*min)
@ UNIT_M
meter
@ UNIT_MMOL
millimole
@ UNIT_NCI_PER_ML
nCi/mL

◆ weights

enum weights

Is data weighted, or are weight factors available with data?

Enumerator
WEIGHTING_UNKNOWN 

Not known; usually assumed that not weighted.

WEIGHTING_OFF 

Not weighted or weights not available (weights for all included samples are 1.0).

WEIGHTING_ON_GENERAL 

Weighted or weights are available, but not specified.

WEIGHTING_ON_COUNTS 

Weights based on counts (Mazoyer et al, 1986).

WEIGHTING_ON_F 

Weights based on sample frequency or frame length.

WEIGHTING_ON_FD 

Weights based on decay and sample frequency or frame length (Thiele et al, 2008).

Definition at line 52 of file tpcextensions.h.

52 {
59 // possibility to add more weighting schemes
60 WEIGHTING_LAST
61} weights;
weights
Is data weighted, or are weight factors available with data?
@ WEIGHTING_OFF
Not weighted or weights not available (weights for all included samples are 1.0).
@ WEIGHTING_ON_FD
Weights based on decay and sample frequency or frame length (Thiele et al, 2008).
@ WEIGHTING_UNKNOWN
Not known; usually assumed that not weighted.
@ WEIGHTING_ON_GENERAL
Weighted or weights are available, but not specified.
@ WEIGHTING_ON_F
Weights based on sample frequency or frame length.
@ WEIGHTING_ON_COUNTS
Weights based on counts (Mazoyer et al, 1986).

Function Documentation

◆ 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
See also
asciiFileRead, asciiFileSize, strTrimLeft, strstrNoQuotation
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 149 of file readasciifile.c.

156 {
157 if(cont!=NULL) *cont=0;
158 if(line==NULL) return 0;
159 char *cptr=(char*)line;
160 int i=strspn(cptr, " \t"); cptr+=i; if(cont!=NULL) *cont=i;
161 if(*cptr!='#') return 0;
162 if(cont==NULL) return 1;
163 cptr++; i=strspn(cptr, " \t"); *cont+=(i+1);
164 return 1;
165}

Referenced by iftPutFromString(), iftPutFromStringWithSpaceSeparator(), and tacFormatDetermine().

◆ asciiFileRead()

char * asciiFileRead ( FILE * fp,
char * data,
size_t maxlen )
extern

Read at most maxlen-1 characters from given file pointer to ASCII text file.

Author
Vesa Oikonen
Returns
Pointer to the string, or NULL in case of an error.
See also
asciiFileSize, asciiCommentLine, fileExist, filenameGetExtension
Parameters
fpFile pointer; rewind() is NOT called here to allow reading data in chunks.
dataPointer to character array in which the data is written; NULL, if memory is to allocated here (in that case remember to free it after use). Terminal zero is added.
maxlenNr of characters to read, and the size of data array (including terminal zero).

Definition at line 117 of file readasciifile.c.

125 {
126 /* Check the input */
127 if(fp==NULL || maxlen<2) return NULL;
128 /* Allocate memory if needed */
129 char *cptr;
130 if(data!=NULL) cptr=data; else {
131 cptr=malloc(maxlen*sizeof(char)); if(cptr==NULL) return NULL;
132 }
133 size_t i=0; int c;
134 while((c=fgetc(fp))!=EOF && i<maxlen-1) cptr[i++]=(char)c;
135 cptr[i]=(char)0; if(i==0) {if(data==NULL) free(cptr); cptr=NULL;}
136 return cptr;
137}

Referenced by csvRead(), iftRead(), and tacFormatDetermine().

◆ asciiFileSize()

size_t asciiFileSize ( FILE * fp,
int * nonprintable )
extern

Get the size of ASCII text file, or size of initial ASCII part of file containing binary data after the text part (in certain image formats).

One NUL character is not counted as binary data, but two already is; this, because equipment failures sometimes lead to data ending with NUL.

Author
Vesa Oikonen
Returns
The number of characters in the initial ASCII part of file. This does not include the terminal zero that would be added to a string.
See also
asciiFileRead, asciiCommentLine, fileExist
Parameters
fpFile pointer; rewind() is called before returning.
nonprintableValue will be set to 1 if reading was stopped at a non-printable character meaning that file may contain a binary part, or to 0 if file contains only printable characters and size of all contents was counted. Enter NULL, if not needed.

Definition at line 26 of file readasciifile.c.

34 {
35 if(nonprintable!=NULL) *nonprintable=0;
36 if(fp==NULL) return(0);
37 size_t n, bn;
38 int c;
39 n=bn=0;
40 while((c=fgetc(fp))!=EOF && n<SIZE_MAX-1 && bn<2) {
41 if(iscntrl(c) && c!=13 && c!=10 && c!=9 && c!=169) {
42 bn++;
43 if(c!=0) {
44 if(nonprintable!=NULL) *nonprintable=1;
45 break;
46 }
47 }
48 n++;
49 }
50 rewind(fp);
51 if(nonprintable!=NULL && bn>1) *nonprintable=1;
52 return n;
53}

Referenced by csvRead(), iftRead(), tacFormatDetermine(), and tacRead().

◆ atofCheck()

int atofCheck ( const char * s,
double * v )
extern

Verifies that argument string at least seems like a valid number.

Both decimal point and comma are accepted. Optional result double value is set to NaN if string was not valid value.

See also
atofVerified, atoiCheck, doubleGetWithUnit, atofList, strCleanSpaces, strIsValidNumber
Returns
0 if successful, and 1 in case of an error.
Parameters
sString which is converted to a double; string must not contain any space characters.
vPointer to the double float; enter NULL, if not needed.

Definition at line 94 of file decpoint.c.

99 {
100 if(v!=NULL) *v=nan("");
101 if(s==NULL) return 1;
102 if(!strIsValidNumber(s)) return 1;
103 char *p; p=strchr(s, ','); if(p==NULL) {*v=atof(s); return 0;}
104 char *s2=strdup(s); p=strchr(s2, ','); *p='.';
105 *v=atof(s2); free(s2); return 0;
106}
int strIsValidNumber(const char *s)
Definition decpoint.c:33
char * strdup(const char *s)
Definition stringext.c:185

Referenced by doubleGetWithUnit(), floatGetWithUnit(), iftGetDoubleValue(), tacReadCarimasTxt(), and tacReadInveonCSV().

◆ atofList()

int atofList ( const char * s1,
const char * s2,
double * x,
int maxn )
extern

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

Returns
The number of double values, or <0 in case of an error.
Author
Vesa Oikonen
See also
strTokenNr, strTokenNCpy, intlistAddFromString, atofCheck, tpcYesNo, doubleCopy, doubleSpanPositives
Parameters
s1Pointer to string from which double values are read.
s2String containing character delimiters
xPointer to a pre-allocated array of doubles.
maxnSize of double list; obligatory. If string contains more values, only maxn values will be read.

Definition at line 150 of file decpoint.c.

160 {
161 if(x==NULL || maxn<=0) return(-1);
162 for(int i=0; i<maxn; i++) x[i]=nan("");
163 if(s1==NULL || s2==NULL) return(0);
164
165 /* Get the nr of tokens */
166 int i, n;
167 n=strTokenNr((char*)s1, s2); if(n<1) return(0);
168 /* Read the values */
169 char tmp[256];
170 double v;
171 for(i=0; i<n && i<maxn; i++) {
172 if(strTokenNCpy(s1, s2, 1+i, tmp, 256)<1) return(-2);
173 v=atofVerified(tmp); if(isnan(v)) return(-3);
174 x[i]=v;
175 }
176 return(i);
177}
double atofVerified(const char *s)
Definition decpoint.c:75
int strTokenNr(const char *s1, const char *s2)
Definition stringext.c:25
int strTokenNCpy(const char *s1, const char *s2, int i, char *s3, int count)
Definition stringext.c:53

◆ atofVerified()

double atofVerified ( const char * s)
extern

Version of atof() which verifies that argument string at least seems like a valid number.

Both decimal point and comma are accepted. Result value is set to NaN if string was not valid value.

See also
atofCheck, doubleGetWithUnit, atoiCheck, strIsValidNumber, tpcYesNo
Returns
converted double value, or NaN in case of an error.
Parameters
sString which is converted to a double; string must not contain any space characters.

Definition at line 75 of file decpoint.c.

78 {
79 if(s==NULL || !strIsValidNumber(s)) return nan("");
80 char *p; p=strchr(s, ','); if(p==NULL) return atof(s);
81 char *s2=strdup(s); p=strchr(s2, ','); *p='.';
82 double t=atof(s2); free(s2); return t;
83}

Referenced by atofList(), dcmImgIsotope(), iftGetDoubleWithUnit(), parReadCSV(), parReadFIT(), parReadRES(), tacRead4DM(), tacReadCSV(), tacReadDFT(), tacReadHRPLUSHC(), tacReadHRRTHC(), tacReadMat(), tacReadPMOD(), tacReadQView(), tacReadSIF(), and tacReadSimple().

◆ atoiCheck()

int atoiCheck ( const char * s,
int * v )
extern

Verifies that argument string at least seems like a valid integer. '\0' must follow the integer part in the string. Optional result integer value is set to 0 if string was not valid value.

See also
atofCheck, intlistAddFromString, strIsValidNumber
Returns
0 if successful, and 1 in case of an error.
Parameters
sString which is converted to an integer; string must not contain any space characters.
vPointer to the integer; enter NULL, if not needed.

Definition at line 25 of file intutil.c.

30 {
31 if(v!=NULL) *v=0;
32 if(s==NULL || strnlen(s, 2)<1) return(1);
33 errno=0; char *tail;
34 *v=strtol(s, &tail, 10);
35 if(errno) {*v=0; return(2);}
36 if(*tail) {*v=0; return(3);}
37 return 0;
38}
size_t strnlen(const char *s, size_t n)
Definition stringext.c:566

Referenced by intlistAddFromString(), and tacReadQView().

◆ ctime_r_int()

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

Convert calendar 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.
See also
time_to_tm, strDateTimeValid, strDateTimeRead
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 119 of file datetime.c.

125 {
126 if(buf==NULL) return(NULL);
127 buf[0]=(char)0;
128 struct tm tm;
129 if(!gmtime_r(t, &tm)) return(NULL);
130 if(!strftime(buf, 20, "%Y-%m-%d %H:%M:%S", &tm)) return(NULL);
131 return(buf);
132}
struct tm * gmtime_r(const time_t *t, struct tm *tm)
Convert time_t to GMT struct tm.
Definition datetime.c:31

Referenced by parWriteRES().

◆ doubleAbsMaxIndex()

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

Find the maximum absolute value in given double array.

Returns
The index [0..n-1] of maximum absolute value in array; 0 is returned also in case of errors.
See also
doubleMaxIndex, doubleGTIndex, doubleGEIndex, doubleRange
Parameters
aPointer to double array.
nLength of array.

Definition at line 377 of file doubleutil.c.

382 {
383 if(a==NULL || n<1) return(0);
384 unsigned int i, mi=0;
385 double mv=nan("");
386 for(i=0; i<n; i++) if(isnan(mv) || fabs(a[i])>mv) {mv=fabs(a[i]); mi=i;}
387 return(mi);
388}

◆ doubleAbsMinIndex()

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

Find the minimum absolute value in given double array.

Returns
The index [0..n-1] of minimum absolute value in array; 0 is returned also in case of errors.
See also
doubleAbsMaxIndex, doubleMinIndex, doubleGTIndex, doubleGEIndex
Parameters
aPointer to double array.
nLength of array.

Definition at line 416 of file doubleutil.c.

421 {
422 if(a==NULL || n<1) return(0);
423 unsigned int i, mi=0;
424 double mv=nan("");
425 for(i=0; i<n; i++) if(isnan(mv) || fabs(a[i])<mv) {mv=fabs(a[i]); mi=i;}
426 return(mi);
427}

Referenced by spectralBFExtract().

◆ doubleArrayMatch()

int doubleArrayMatch ( const double * a1,
const double * a2,
const unsigned int n,
const double lim )
extern

Verifies that given two double arrays have the same values 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
doubleMatch, doubleMatchRel, doubleMachEps, statMeanSD
Parameters
a1First array.
a2Second array.
nLength of arrays.
limLimit for absolute difference (if <0 then test will fail every time).

Definition at line 51 of file doubleutil.c.

60 {
61 if(a1==NULL || a2==NULL || n<1) return 0;
62 for(unsigned int i=0; i<n; i++) if(!doubleMatch(a1[i], a2[i], lim)) return 0;
63 return 1;
64}
int doubleMatch(const double v1, const double v2, const double lim)
Definition doubleutil.c:27

◆ doubleCopy()

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

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

See also
floatCopy, doubleCopyFinite
Parameters
tTarget array.
sSource array.
nLength of arrays.

Definition at line 117 of file doubleutil.c.

124 {
125 unsigned int i;
126 if(t==NULL || s==NULL || n<1) return;
127 for(i=0; i<n; i++) t[i]=s[i];
128}

Referenced by nloptIATGO(), nloptMPSO(), and nloptSimplexARRS().

◆ doubleCopyFinite()

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

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

See also
doubleCopy
Returns
The number of finite values that were copied.
Parameters
tTarget array.
sSource array.
nLength of arrays.

Definition at line 136 of file doubleutil.c.

143 {
144 unsigned int i, tn=0;
145 if(t==NULL || s==NULL || n<1) return(0);
146 for(i=0; i<n; i++) if(isfinite(s[i])) t[tn++]=s[i];
147 return(tn);
148}

◆ 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
floatCSpanPositives, doubleSpanPositives, atofList
Parameters
aPointer to the array.
nLength of the array.

Definition at line 320 of file doubleutil.c.

325 {
326 if(a==NULL || n<1) return(0);
327 int i=0;
328 for(i=0; i<n; i++) if(a[i]>0.0) break;
329 return(i);
330}

Referenced by spectralBFExtract(), and spectralBFNr().

◆ doubleGEIndex()

unsigned int doubleGEIndex ( double * a,
const unsigned int n,
double lim )
extern

Get the index of first array value greater or equal than given limit.

Returns
The index, or n, if not found.
See also
doubleGTIndex, doubleMaxIndex, doubleMinIndex, fitLine, statMeanSD
Parameters
aPointer to an array of values.
nThe number of samples (length of a[]).
limThe limit value.

Definition at line 435 of file doubleutil.c.

442 {
443 if(a==NULL || n<1) return(n);
444 for(unsigned int i=0; i<n; i++) if(a[i]>=lim) return(i);
445 return(n);
446}

◆ doubleGetWithUnit()

int doubleGetWithUnit ( const char * s,
double * v,
int * u )
extern

Reads numerical value and its unit from argument string.

Both decimal point and comma are accepted. Optional result double value is set to NaN if string was not valid value. Optional unit is set to UNIT_UNKNOWN, if not valid or not found.

Returns
0 if numerical value successfully read, and 1 in case of an error.
See also
floatGetWithUnit, atofVerified, atofCheck
Parameters
sString from where double and unit is read; string must not contain any extra space characters.
vPointer to the double float; enter NULL, if not needed.
uPointer to int for unit code; enter NULL, if not needed.

Definition at line 272 of file doubleutil.c.

280 {
281 if(v!=NULL) *v=nan("");
282 if(u!=NULL) *u=UNIT_UNKNOWN;
283 if(s==NULL) return 1;
284 int n=strTokenNr(s, " \t"); if(n==0 || n>2) return 1;
285 if(n==1) return(atofCheck(s, v)); // no unit
286 /* separate number and unit */
287 char buf[64];
288 n=strTokenNCpy(s, " \t", 1, buf, 64);
289 if(atofCheck(buf, v)) return 1;
290 if(u==NULL) return 0;
291 n=strTokenNCpy(s, " \t", 2, buf, 64);
292 *u=unitIdentify(buf);
293 return 0;
294}
int atofCheck(const char *s, double *v)
Definition decpoint.c:94
int unitIdentify(const char *s)
Definition units.c:162

Referenced by iftCheckKeyValue(), and iftCheckKeyValues().

◆ doubleGTIndex()

unsigned int doubleGTIndex ( double * a,
const unsigned int n,
double lim )
extern

Get the index of first array value greater than given limit.

Returns
The index, or n, if not found.
See also
doubleGEIndex, doubleMaxIndex, doubleMinIndex, fitLine, statMeanSD, doubleMatch
Parameters
aPointer to an array of values.
nThe number of samples (length of a[]).
limThe limit value.

Definition at line 452 of file doubleutil.c.

459 {
460 if(a==NULL || n<1) return(n);
461 for(unsigned int i=0; i<n; i++) if(a[i]>lim) return(i);
462 return(n);
463}

◆ 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
floatMachEps, doubleMatchRel, doubleMatch, factorial

Definition at line 105 of file doubleutil.c.

106{
107 double macheps=1.0;
108 do {macheps/=2.0;} while((1.0+macheps/2.0)!=1.0);
109 return(macheps);
110}

Referenced by householder_transform(), nlopt1D(), nloptFixedNr(), nloptLimitFixedNr(), and nloptPowellBrent().

◆ 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
floatMatch, doubleMatchRel, doubleMachEps, atofCheck, statMeanSD
Parameters
v1First value.
v2Second value.
limLimit for absolute difference (if <0 then test will fail every time).

Definition at line 27 of file doubleutil.c.

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

Referenced by doubleArrayMatch(), parCompareParameters(), parCompareWSS(), parIsFitRange(), tacCheckX1X2X(), tacCompareConc(), tacCompareTimes(), tacCompareWeights(), and tacReadQView().

◆ 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
floatMatchRel, doubleMatch, doubleMachEps
Parameters
v1First value.
v2Second value.
limLimit for relative difference (if <0 then test will fail every time).

Definition at line 77 of file doubleutil.c.

84 {
85 if(isnan(v1) && isnan(v2)) return 1;
86 if(isnan(v1) || isnan(v2)) return 0;
87 if(v1==v2) return 1;
88 if(isnan(lim)) return 0;
89 double mean;
90 mean=0.5*(v1+v2); if(!isnormal(mean)) return 0;
91 if(fabs((v1-v2)/mean)<=lim) return 1;
92 return 0;
93}

Referenced by parCompareParameters(), parCompareWSS(), tacCompareConc(), tacCompareTimes(), and tacCompareWeights().

◆ 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.
See also
floatMaxIndex, doubleSpanPositives, doubleCSpanPositives, doubleGTIndex, doubleRange
Parameters
aPointer to double array.
nLength of array.

Definition at line 357 of file doubleutil.c.

362 {
363 if(a==NULL || n<1) return(0);
364 unsigned int i, mi=0;
365 double mv=nan("");
366 for(i=0; i<n; i++) if(isnan(mv) || a[i]>mv) {mv=a[i]; mi=i;}
367 return(mi);
368}

◆ 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
floatMean, doubleWMean, doubleSum, doubleMaxIndex, statMeanSD, statMedian
Parameters
aPointer to double array.
nLength of array.

Definition at line 224 of file doubleutil.c.

229 {
230 if(a==NULL || n<1) return(nan(""));
231 double s=0.0;
232 unsigned int i, ci=0;
233 for(i=0; i<n; i++) if(!isnan(a[i])) {ci++; s+=a[i];}
234 if(ci<1) return(nan(""));
235 return(s/(double)ci);
236}

◆ doubleMinIndex()

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

Find the minimum value in given double array.

Returns
The index [0..n-1] of minimum value in array; 0 is returned also in case of errors.
See also
doubleMaxIndex, doubleAbsMinIndex, doubleRange
Parameters
aPointer to double array.
nLength of array.

Definition at line 396 of file doubleutil.c.

401 {
402 if(a==NULL || n<1) return(0);
403 unsigned int i, mi=0;
404 double mv=nan("");
405 for(i=0; i<n; i++) if(isnan(mv) || a[i]<mv) {mv=a[i]; mi=i;}
406 return(mi);
407}

◆ doubleNaNs()

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

Check the number of NaNs in a double array.

See also
doubleNonzeroes, doubleCopyFinite, doubleRange, doubleMean
Returns
The number of NaNs.
Parameters
aPointer to double array.
nLength of array.

Definition at line 156 of file doubleutil.c.

161 {
162 if(a==NULL || n<1) return(0);
163 unsigned int i, nn=0;
164 for(i=0; i<n; i++) if(isnan(a[i])) nn++;
165 return(nn);
166}

◆ doubleNonzeroes()

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

Find the number of non-zero values in given double array. Negative values are counted, but NaNs are not.

Returns
The number of non-zero values in array; 0 is returned also in case of errors.
See also
floatNonzeroes, doubleSpanPositives, doubleNaNs
Parameters
aPointer to double array.
nLength of array.

Definition at line 339 of file doubleutil.c.

344 {
345 if(a==NULL || n<1) return(0);
346 unsigned int i, m=0;
347 for(i=0; i<n; i++) if(fabs(a[i])>0.0) m++;
348 return(m);
349}

◆ doubleRange()

unsigned int doubleRange ( double * a,
const unsigned int n,
double * amin,
double * amax )
extern

Get the range of finite values in a double array.

See also
doubleMaxIndex, doubleMinIndex, doubleNonzeroes, doubleNaNs, doubleMean, statMedian
Returns
The number of finite values in the array, or 0 in case of an error.
Parameters
aPointer to double array.
nLength of array.
aminPointer to the double float where minimum value is stored; enter NULL, if not needed.
amaxPointer to the double float where maximum value is stored; enter NULL, if not needed.

Definition at line 174 of file doubleutil.c.

183 {
184 if(amin!=NULL) *amin=nan("");
185 if(amax!=NULL) *amax=nan("");
186 if(a==NULL || n<1) return(0);
187
188 double mi=nan(""), ma=nan("");
189 unsigned int i, nn=0;
190 for(i=0; i<n; i++) if(isfinite(a[i])) {
191 nn++;
192 if(!isfinite(mi) || mi>a[i]) mi=a[i];
193 if(!isfinite(ma) || ma<a[i]) ma=a[i];
194 }
195 if(amin!=NULL) *amin=mi;
196 if(amax!=NULL) *amax=ma;
197 return(nn);
198}

◆ 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 non-positive value in the given array.
See also
floatSpanPositives, doubleCSpanPositives, atofList, doubleNonzeroes
Parameters
aPointer to the array.
nLength of the array.

Definition at line 302 of file doubleutil.c.

307 {
308 if(a==NULL || n<1) return(0);
309 int i=0;
310 for(i=0; i<n; i++) if(!(a[i]>0.0)) break;
311 return(i);
312}

Referenced by spectralBFExtract(), and spectralBFNr().

◆ 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
floatSum, doubleMean, doubleMaxIndex
Parameters
aPointer to double array.
nLength of array.

Definition at line 206 of file doubleutil.c.

211 {
212 double s=0.0;
213 if(a==NULL || n<1) return(s);
214 for(unsigned int i=0; i<n; i++) if(!isnan(a[i])) s+=a[i];
215 return(s);
216}

Referenced by spectralBFExtract().

◆ doubleWMean()

double doubleWMean ( double * a,
double * w,
const unsigned int n )
extern

Calculate the weighted mean of values in given double array.

Returns
The mean of array values, or NaN in case of an error.
See also
doubleMean, floatMean, doubleSum, doubleMaxIndex, statMeanSD
Parameters
aPointer to double array to calculated weighted mean from.
wPointer to double array containing the weights. Negative or NaN weight is interpreted as zero weight.
nLength of arrays.

Definition at line 244 of file doubleutil.c.

252 {
253 if(a==NULL || w==NULL || n<1) return(nan(""));
254 double s=0.0, ws=0.0;
255 unsigned int i, ci=0;
256 for(i=0; i<n; i++) if(isnormal(a[i]) && isnormal(w[i]) && w[i]>0.0) {
257 ci++; s+=w[i]*a[i]; ws+=w[i];}
258 if(ci<1 || !(ws>0.0)) return(nan(""));
259 return(s/ws);
260}

Referenced by spectralBFExtract().

◆ endianLittle()

int endianLittle ( )
extern

Check whether current platform uses little endian byte order.

See also
swap, swabip, swawbip, swawip
Returns
Returns 1, if current platform is little endian, and 0 if not.

Definition at line 53 of file endian.c.

54{
55 //int x=1;
56 //if(*(char *)&x==1) return(1); else return(0);
57 if(endianness()==ENDIAN_LITTLE) return(1); else return(0);
58}
int endianness()
Definition endian.c:26

Referenced by anaReadHeader(), dcmFileWrite(), dcmitemGetInt(), dcmitemGetReal(), dcmReadFileTag(), dcmReadFileVL(), dcmReadFileVRVL(), dcmValueString(), dcmWriteFileTag(), dcmWriteFileVRVL(), ecatMListRead(), ecatReadMainheader(), ecatWriteMainheader(), imgReadNifti(), imgSetNiftiHeader(), niftiReadHeader(), and niftiWriteHeader().

◆ endianness()

int endianness ( )
extern

Detect endianness at run-time. From https://sourceforge.net/p/predef/wiki/Endianness/

Returns
Returns ENDIAN_UNKNOWN, ENDIAN_BIG, ENDIAN_LITTLE, ENDIAN_BIG_WORD, or ENDIAN_LITTLE_WORD.

Definition at line 26 of file endian.c.

27{
28 union {
29 uint32_t value;
30 uint8_t data[sizeof(uint32_t)];
31 } number;
32
33 number.data[0] = 0x00;
34 number.data[1] = 0x01;
35 number.data[2] = 0x02;
36 number.data[3] = 0x03;
37
38 switch (number.value) {
39 case UINT32_C(0x00010203): return ENDIAN_BIG;
40 case UINT32_C(0x03020100): return ENDIAN_LITTLE;
41 case UINT32_C(0x02030001): return ENDIAN_BIG_WORD;
42 case UINT32_C(0x01000302): return ENDIAN_LITTLE_WORD;
43 default: return ENDIAN_UNKNOWN;
44 }
45}

Referenced by endianLittle().

◆ errorMsg()

char * errorMsg ( tpcerror e)
extern

Return pointer to error message specified with the error code.

Returns
pointer to the error message string.
See also
tpcerror, statusPrint
Author
Vesa Oikonen
Parameters
eError code
See also
tpcerror.

Definition at line 68 of file statusmsg.c.

71 {
72 if(e<TPCERROR_OK || e>=TPCERROR_LAST) return NULL;
73 return tpcerrormsg[e];
74}

Referenced by imgRead(), and nloptIATGO().

◆ factorial()

unsigned int factorial ( unsigned int n)
extern

Calculate factorial of given number.

See also
lfactorial, igam, igamc
Returns
Returns factorial n!, or zero if factorial would cause wrap-around.
Parameters
nInteger n, from which the factorial is calculated.
Note
Wrap-around will occur if n>12.

Definition at line 46 of file intutil.c.

51 {
52 if(n<1) return(1);
53 if(n>12) return(0);
54 return(n*factorial(n-1));
55}
unsigned int factorial(unsigned int n)
Definition intutil.c:46

Referenced by factorial().

◆ filenameGetExtension()

char * filenameGetExtension ( const char * s)
extern

Get the last extension of a file name.

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

See also
filenameGetExtensions, filenameRmExtension, strTrimLeft
Returns
Pointer to the file name extension starting with '.', or NULL if no extension is found.
Parameters
sPointer to string; string is not edited here.

Definition at line 178 of file filename.c.

181 {
182 if(s==NULL || strnlen(s, 1)<1) return((char*)NULL);
183 /* Identify path */
184 char *pptr=strrchr(s, '/'); if(pptr==NULL) pptr=strrchr(s, '\\');
185 if(pptr==NULL) pptr=(char*)s; else pptr++;
186 /* Search for the last '.' after the path */
187 char *cptr=strrchr(pptr, '.'); if(cptr==NULL) return(cptr);
188 /* If file name starts with '.', that is not counted as extension */
189 if(strlen(pptr)==strlen(cptr)) return((char*)NULL);
190 return(cptr);
191}

Referenced by abssIdFromFName(), imgWriteNifti(), micropetExists(), niftiBasename(), and tacRead().

◆ filenameGetExtensions()

char * filenameGetExtensions ( const char * s)
extern

Get all extensions of a file name.

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

See also
filenameGetExtension, filenameRmExtensions, strTrimLeft
Returns
Pointer to the file name extension starting with '.', or NULL if no extension is found.
Parameters
sPointer to string; string is not edited here.

Definition at line 203 of file filename.c.

206 {
207 if(s==NULL || strnlen(s, 1)<1) return((char*)NULL);
208 /* Identify path */
209 char *pptr=strrchr(s, '/'); if(pptr==NULL) pptr=strrchr(s, '\\');
210 if(pptr==NULL) pptr=(char*)s; else pptr++;
211 /* Search for the last '.' after the path, ignoring first character in case file name starts with '.' */
212 char *cptr=strchr(pptr+1, '.');
213 return(cptr);
214}

Referenced by imgFormatFromFName(), and parFormatFromExtension().

◆ filenameRmExtension()

int filenameRmExtension ( char * s)
extern

Remove the last extension from file name.

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

Definition at line 71 of file filename.c.

74 {
75 if(s==NULL || strnlen(s, 1)<1) return(0);
76 char *cptr;
77 cptr=strrchr(s, '.'); if(cptr==NULL) return(0);
78 if(cptr[1]=='/' || cptr[1]=='\\') return(0);
79 *cptr=(char)0;
80 return(1);
81}

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

◆ filenameRmExtensions()

void filenameRmExtensions ( char * s)
extern

Remove all extensions from file name.

See also
filenameGetExtensions, filenameRmExtension, strdelstr, strTrimLeft
Author
Vesa Oikonen
Parameters
sPointer to string.

Definition at line 89 of file filename.c.

92 {
93 if(s==NULL || strnlen(s, 1)<1) return;
94 while(filenameRmExtension(s)) {}
95 return;
96}
int filenameRmExtension(char *s)
Definition filename.c:71

Referenced by studynrFromFilename().

◆ filenameRmFile()

void filenameRmFile ( char * s)
extern

Remove file name from file name string including path, leaving only path without trailing '/'. If there is no path, then result is ".". For root path the result string is empty. See also POSIX function dirname() in libgen.h.

See also
filenameRmPath, filenameRmExtensions, pathExist
Author
Vesa Oikonen
Parameters
sPointer to string.

Definition at line 44 of file filename.c.

47 {
48 if(s==NULL) return;
49 unsigned int len=strnlen(s, FILENAME_MAX);
50 if(len==0) return;
51 //if(len==1) {s[0]='.'; return;}
52 char *cptr;
53 cptr=strrchr(s, '/'); if(cptr==NULL) cptr=strrchr(s, '\\');
54 if(cptr!=NULL) {
55 *cptr=(char)0;
56 if(strcmp(s, "/")==0 || strcmp(s, "\\")==0) s[0]=(char)0;
57 return;
58 }
59 if(strcmp(s, "..")==0) return;
60 s[0]='.'; s[1]=(char)0;
61 return;
62}

Referenced by dcmFileList(), and imgWriteNifti().

◆ filenameRmPath()

void filenameRmPath ( char * s)
extern

Remove path from file name. See also POSIX function basename() in libgen.h.

See also
filenameRmFile, filenameRmExtensions, strTrimleft
Author
Vesa Oikonen
Parameters
sPointer to string.

Definition at line 20 of file filename.c.

23 {
24 if(s==NULL || strnlen(s, 1)<1) return;
25 char *cptr;
26 cptr=strrchr(s, '/'); if(cptr==NULL) cptr=strrchr(s, '\\');
27 if(cptr==NULL) return;
28 cptr++;
29 int i, n=strlen(cptr);
30 for(i=0; i<n; i++, cptr++) s[i]=*cptr;
31 s[i]=(char)0;
32 return;
33}

Referenced by imgWriteNifti(), niftiCreateFNames(), studynrFromFilename(), tpcHtmlUsage(), tpcPrintBuild(), tpcPrintUsage(), and tpcProgramName().

◆ floatCopy()

void floatCopy ( float * t,
float * s,
const unsigned int n )
extern

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

See also
doubleCopy
Parameters
tTarget array.
sSource array.
nLength of arrays.

Definition at line 94 of file floatutil.c.

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

◆ floatCSpanPositives()

int floatCSpanPositives ( float * 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
doubleCSpanPositives, floatSpanPositives, atofList
Parameters
aPointer to the array.
nLength of the array.

Definition at line 228 of file floatutil.c.

233 {
234 if(a==NULL || n<1) return(0);
235 int i=0;
236 for(i=0; i<n; i++) if(a[i]>0.0) break;
237 return(i);
238}

◆ floatGetWithUnit()

int floatGetWithUnit ( const char * s,
float * v,
int * u )
extern

Reads numerical value and its unit from argument string.

Both decimal point and comma are accepted. Optional result float value is set to NaN if string was not valid value. Optional unit is set to UNIT_UNKNOWN, if not valid or not found.

Returns
0 if numerical value successfully read, and 1 in case of an error.
See also
doubleGetWithUnit, atofVerified, atofCheck
Parameters
sString from where float and unit is read; string must not contain any extra space characters.
vPointer to the float; enter NULL, if not needed.
uPointer to int for unit code; enter NULL, if not needed.

Definition at line 174 of file floatutil.c.

182 {
183 if(v!=NULL) *v=nanf("");
184 if(u!=NULL) *u=UNIT_UNKNOWN;
185 if(s==NULL) return 1;
186 int n=strTokenNr(s, " \t"); if(n==0 || n>2) return 1;
187 if(n==1) { // no unit
188 double dv;
189 if(atofCheck(s, &dv)) return 1;
190 *v=(float)dv; return 0;
191 }
192 /* separate number and unit */
193 char buf[64];
194 n=strTokenNCpy(s, " \t", 1, buf, 64);
195 double dv;
196 if(atofCheck(buf, &dv)) return 1;
197 *v=(float)dv;
198 if(u==NULL) return 0;
199 n=strTokenNCpy(s, " \t", 2, buf, 64);
200 *u=unitIdentify(buf);
201 return 0;
202}

◆ floatMachEps()

float floatMachEps ( )
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 FLT_EPSILON and DBL_EPSILON in float.h.

Returns
Estimate of machine epsilon.
Author
Vesa Oikonen
See also
doubleMachEps, floatMatchRel, floatMatch

Definition at line 82 of file floatutil.c.

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

◆ floatMatch()

int floatMatch ( const float v1,
const float v2,
const float lim )
extern

Verifies that given two floats 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
doubleMatch, floatMatchRel, floatMachEps, atofCheck
Parameters
v1First value
v2Second value
limLimit for absolute difference (if <0 then test will fail every time)

Definition at line 27 of file floatutil.c.

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

Referenced by imgCompareConc(), imgCompareTimes(), and imgReadDICOM().

◆ floatMatchRel()

int floatMatchRel ( const float v1,
const float v2,
const float lim )
extern

Verifies that given two floats 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
doubleMatchRel, floatMatch, floatMachEps
Parameters
v1First value.
v2Second value.
limLimit for relative difference (if <0 then test will fail every time).

Definition at line 54 of file floatutil.c.

61 {
62 if(isnan(v1) && isnan(v2)) return 1;
63 if(isnan(v1) || isnan(v2)) return 0;
64 if(v1==v2) return 1;
65 if(isnan(lim)) return 0;
66 float mean;
67 mean=0.5*(v1+v2); if(!isnormal(mean)) return 0;
68 if(fabsf((v1-v2)/mean)<=lim) return 1;
69 return 0;
70}

Referenced by imgCompareConc(), and imgCompareTimes().

◆ floatMaxIndex()

unsigned int floatMaxIndex ( float * a,
const unsigned int n )
extern

Find the maximum value in given float array.

Returns
The index [0..n-1] of maximum value in array; 0 is returned also in case of errors.
See also
doubleMaxIndex, floatSpanPositives, floatCSpanPositives
Parameters
aPointer to float array.
nLength of array.

Definition at line 113 of file floatutil.c.

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

◆ floatMean()

float floatMean ( float * a,
const unsigned int n )
extern

Calculate the mean of values in given float array.

Returns
The mean of array values, or NaN in case of an error.
See also
doubleMean, floatSum, floatMaxIndex, fstatMeanSD
Parameters
aPointer to float array.
nLength of array.

Definition at line 150 of file floatutil.c.

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

◆ floatNonzeroes()

unsigned int floatNonzeroes ( float * a,
const unsigned int n )
extern

Find the number of non-zero values in given float array. Negative values are counted, but NaNs are not.

Returns
The number of non-zero values in array; 0 is returned also in case of errors.
See also
doubleNonzeroes, floatSpanPositives
Parameters
aPointer to float array.
nLength of array.

Definition at line 247 of file floatutil.c.

252 {
253 if(a==NULL || n<1) return(0);
254 unsigned int i, m=0;
255 for(i=0; i<n; i++) if(fabsf(a[i])>0.0) m++;
256 return(m);
257}

Referenced by imgContents().

◆ floatSpanPositives()

int floatSpanPositives ( float * 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
doubleSpanPositives, floatCSpanPositives, atofList, floatNonzeroes
Parameters
aPointer to the array.
nLength of the array.

Definition at line 210 of file floatutil.c.

215 {
216 if(a==NULL || n<1) return(0);
217 int i=0;
218 for(i=0; i<n; i++) if(!(a[i]>0.0)) break;
219 return(i);
220}

◆ floatSum()

float floatSum ( float * a,
const unsigned int n )
extern

Calculate the sum of values in given float array.

Returns
The sum of array values.
See also
doubleSum, floatMean, floatMaxIndex
Parameters
aPointer to float array.
nLength of array.

Definition at line 132 of file floatutil.c.

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

◆ fncasematch()

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

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

See also
fnmatch, fileExist, pathExist
Returns
1 if strings do match and 0 if not.
Parameters
fnamefile name that is evaluated.
keykey string which may contain wild-cards '?' and '*'.

Definition at line 139 of file filename.c.

144 {
145 if(fname==NULL || key==NULL) return(0);
146 char *key_ptr=NULL, *fname_ptr=NULL;
147
148 while((*key)&&(*fname)) {
149 if((*key=='?')||(toupper((int)*key)==toupper((int)*fname))) {
150 key++; fname++;
151 } else if(*key=='*') {
152 if(toupper((int)*(key+1))==toupper((int)*fname)) {
153 key_ptr=(char*)key++; fname_ptr=(char*)fname+1;
154 } else {
155 fname++;
156 if(*(key+1)=='?') {key_ptr=(char*)key++; fname_ptr=(char*)fname;}
157 }
158 } else if((key_ptr!=NULL) && (*fname_ptr)) {
159 return(fnmatch(key_ptr, fname_ptr));
160 } else {
161 return(0);
162 }
163 }
164 if((*fname)&&(key_ptr!=NULL)) {return(fnmatch(key_ptr, fname_ptr));}
165 else {if(*key=='*') key++; return(toupper((int)*key)==toupper((int)*fname));}
166}
int fnmatch(const char *fname, const char *key)
Definition filename.c:104

Referenced by roinameMatch().

◆ fnmatch()

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

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

See also
fncasematch, fileExist, pathExist, roinameMatch, strncpyClean
Returns
1 if strings do match and 0 if not.
Parameters
fnamefile name that is evaluated.
keykey string which may contain wild cards '?' and '*'.

Definition at line 104 of file filename.c.

109 {
110 if(fname==NULL || key==NULL) return(0);
111 char *key_ptr=NULL, *fname_ptr=NULL;
112
113 while((*key)&&(*fname)) {
114 if((*key=='?')||(*key==*fname)) {
115 key++; fname++;
116 } else if(*key=='*') {
117 if(*(key+1)==*fname) {key_ptr=(char*)key++; fname_ptr=(char*)fname+1;
118 } else {
119 fname++;
120 if(*(key+1)=='?') {key_ptr=(char*)key++; fname_ptr=(char*)fname;}
121 }
122 } else if((key_ptr!=NULL) && (*fname_ptr)) {
123 return(fnmatch(key_ptr, fname_ptr));
124 } else {
125 return(0);
126 }
127 }
128 if((*fname)&&(key_ptr!=NULL)) {return(fnmatch(key_ptr, fname_ptr));}
129 else {if(*key=='*') key++; return(*key==*fname);}
130}

Referenced by fncasematch(), and fnmatch().

◆ 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.

See also
localtime_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 31 of file datetime.c.

36 {
37 struct tm *ltm=gmtime(t);
38 if(ltm==NULL || tm==NULL) return(NULL);
39 *tm=*ltm; tm->tm_isdst=-1;
40 return tm;
41}

Referenced by ctime_r_int(), tacReadGEMS(), and timegm().

◆ intlistAdd()

int intlistAdd ( INTLIST * l,
const int v,
const int ifnew )
extern

Add one integer to the integer array in INTLIST structure.

See also
intlistInit, intlistFree, intlistSort, intlistAddFromString, strncatInt
Author
Vesa Oikonen
Returns
Returns the nr of added integers (either 0 or 1), or <0 in case of an error.
Parameters
lPointer to initiated or filled INTLIST structure.
vInteger value to add.
ifnewAdd integer to the list only if it is new (0=no, 1=yes).

Definition at line 108 of file intutil.c.

115 {
116 if(l==NULL) return(-1);
117 /* If only new value is to be added, then check that this is new */
118 if(ifnew!=0) {for(int i=0; i<l->nr; i++) if(l->i[i]==v) return(0);}
119 /* Add value to list if there is space left, and quit */
120 if(l->_nr>l->nr) {l->i[l->nr++]=v; return(1);}
121 /* Allocate more space */
122 if(l->_nr==0) l->i=(int*)malloc(10*sizeof(int));
123 else l->i=(int*)realloc(l->i, (10+l->_nr)*sizeof(int));
124 if(l->i==NULL) {l->nr=l->_nr=0; return(-2);}
125 l->_nr+=10;
126 /* Add value to list */
127 l->i[l->nr++]=v;
128 return(1);
129}

Referenced by intlistAddFromString(), and intlistExpandFromString().

◆ intlistAddFromString()

int intlistAddFromString ( const char * s1,
const char * s2,
INTLIST * l,
const int ifnew )
extern

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

See also
strTokenNr, strTokenNCpy, intlistAdd, intlistInit, intlistFree, intlistSort, intlistExpandFromString.
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 INTLIST structure; previous contents are preserved.
ifnewAdd integer to the list only if it is new (0=no, 1=yes).

Definition at line 156 of file intutil.c.

165 {
166 if(l==NULL) return(-1);
167 if(s1==NULL || s2==NULL) return(0);
168
169 /* Get the nr of tokens */
170 int i, j, m, n, v;
171 n=strTokenNr((char*)s1, s2); if(n<1) return(0);
172 /* Read the values */
173 char tmp[128];
174 for(i=j=0; i<n; i++) {
175 if(strTokenNCpy(s1, s2, 1+i, tmp, 128)<1) return(-2);
176 if(atoiCheck(tmp, &v)) return(-3);
177 m=intlistAdd(l, v, ifnew); if(m<0) return(-4);
178 j+=m;
179 }
180 return(j);
181}
int atoiCheck(const char *s, int *v)
Definition intutil.c:25
int intlistAdd(INTLIST *l, const int v, const int ifnew)
Definition intutil.c:108

◆ intlistExpandFromString()

int intlistExpandFromString ( const char * s1,
const char * s2,
INTLIST * l,
const int ifnew )
extern

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

See also
strTokenNCpy, intlistAddFromString, intlistInit, intlistFree, intlistSort, strIsValidNumber
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 INTLIST struct; previous contents are preserved.
ifnewAdd integer to the list only if it is new (0=no, 1=yes).

Definition at line 190 of file intutil.c.

200 {
201 if(l==NULL) return(-1);
202 if(s1==NULL || s2==NULL) return(0);
203
204 /* Get the nr of tokens */
205 int n=strTokenNr((char*)s1, s2); if(n<1) return(0);
206 /* Read the values */
207 char tmp[128], tmp2[128], *t, *tail;
208 int i, j, m, first, last, sw;
209 for(i=j=0; i<n; i++) {
210 if(strTokenNCpy(s1, s2, 1+i, tmp, 128)<1) return(-2);
211 t=tmp; errno=0;
212 first=strtol(t, &tail, 10); if(errno) return(-3);
213 if(*tail) {
214 strcpy(tmp2, tail); t=tmp2;
215 if(*t=='-') t++;
216 else if(*t=='.') {t++; if(*t=='.') t++; else return(-4);}
217 else return(-5);
218 if(!*t) return(-6);
219 last=strtol(t, &tail, 10); if(errno) return(-7);
220 if(*tail) return(-8);
221 } else {
222 last=first;
223 }
224
225 if(first>last) {sw=first; first=last; last=sw;}
226 for(int v=first; v<=last; v++) {
227 m=intlistAdd(l, v, ifnew); if(m<0) return(-10);
228 j+=m;
229 }
230 }
231 return(j);
232}

Referenced by parSelectParameters(), and parSelectTACs().

◆ intlistFree()

void intlistFree ( INTLIST * l)
extern

Free memory allocated for INTLIST. All data is cleared.

See also
intlistInit
Author
Vesa Oikonen
Parameters
lPointer to INTLIST structure

Definition at line 92 of file intutil.c.

95 {
96 if(l==NULL) return;
97 free(l->i);
98 intlistInit(l);
99}
void intlistInit(INTLIST *l)
Definition intutil.c:80

Referenced by parSelectParameters(), and parSelectTACs().

◆ intlistInit()

void intlistInit ( INTLIST * l)
extern

Initiate the INTLIST structure before any use.

See also
intlistFree, intlistAdd, intlistSort
Author
Vesa Oikonen
Parameters
lPointer to INTLIST.

Definition at line 80 of file intutil.c.

83 {
84 if(l==NULL) return;
85 l->nr=0; l->_nr=0;
86 l->i=NULL;
87}

Referenced by intlistFree(), parSelectParameters(), and parSelectTACs().

◆ intlistSort()

void intlistSort ( INTLIST * l)
extern

Sort the integer array in INTLIST structure.

See also
intlistInit, intlistFree, intlistAdd
Author
Vesa Oikonen
Parameters
lPointer to INTLIST structure.

Definition at line 137 of file intutil.c.

140 {
141 if(l==NULL || l->i==NULL || l->nr<2) return;
142 int i, j, v;
143 for(i=0; i<l->nr; i++) for(j=i+1; j<l->nr; j++) {
144 if(l->i[i]>l->i[j]) {v=l->i[i]; l->i[i]=l->i[j]; l->i[j]=v;}
145 }
146}

Referenced by parSelectParameters(), and parSelectTACs().

◆ 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).
See also
doubleMachEps, igam, igamc
Parameters
xParameter for the inverse complementary error function.

Definition at line 473 of file doubleutil.c.

476 {
477 static const double a[] = {
478 -3.969683028665376E+01, 2.209460984245205E+02, -2.759285104469687E+02,
479 1.383577518672690E+02, -3.066479806614716E+01, 2.506628277459239
480 };
481 static const double b[] = {
482 -5.447609879822406E+01, 1.615858368580409E+02, -1.556989798598866E+02,
483 6.680131188771972E+01, -1.328068155288572E+01
484 };
485 static const double c[] = {
486 -7.784894002430293E-03, -3.223964580411365E-01, -2.400758277161838,
487 -2.549732539343734, 4.374664141464968, 2.938163982698783
488 };
489 static const double d[] = {
490 7.784695709041462E-03, 3.224671290700398E-01, 2.445134137142996, 3.754408661907416
491 };
492 double y, e, u;
493 x/=2.0;
494 if(x<0.02425) {
495 double q=sqrt(-2.0 * log(x));
496 y = (((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5])
497 / ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0);
498 } else if(x<=0.97575) {
499 double q=x-0.5;
500 double r=q*q;
501 y = (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q
502 / (((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1.0);
503 } else {
504 double q=sqrt(-2.0 * log(1.0-x));
505 y = -(((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5])
506 / ((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0);
507 }
508 e=0.5*erfc(-y/M_SQRT2)-x;
509 u=(e)*M_SQRT2*M_PI*exp(0.5*y*y);
510 y-=u/(1.0 + 0.5*y*u);
511 return(fabs(y/M_SQRT2));
512}

◆ lfactorial()

unsigned long long int lfactorial ( unsigned long long int n)
extern

Calculate factorial of given number.

See also
factorial, igam, igamc
Returns
Returns factorial n!, or zero if factorial would cause wrap-around.
Parameters
nInteger n, from which the factorial is calculated.
Note
Wrap-around will occur if n>20.

Definition at line 63 of file intutil.c.

68 {
69 if(n<1) return(1);
70 if(n>20) return(0);
71 return(n*lfactorial(n-1));
72}
unsigned long long int lfactorial(unsigned long long int n)
Definition intutil.c:63

Referenced by lfactorial(), mfEvalInt(), and mfEvalY().

◆ 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 54 of file datetime.c.

59 {
60 struct tm *ltm=localtime(t);
61 if(ltm==NULL || tm==NULL) return(NULL);
62 *tm=*ltm; tm->tm_isdst=-1;
63 return tm;
64}

Referenced by tacReadScanditronics().

◆ roinameAddField()

char * roinameAddField ( char * roiname,
const char * field,
const unsigned int in,
const unsigned int count )
extern

Add a new field into given position inside an existing ROI name. Space character and '_' are accepted as field separators.

Returns
Returns pointer to the edited ROI name, or NULL in case of an error.
See also
roinameSubpart, roinameEditByTemplate, roinameExists, roinameMatch, strdelstr
Parameters
roinameROI name string which will be edited.
fieldString which will be added as a new field in roiname; can be empty in order to add empty field, but NULL is not accepted.
inField index [0..n] for which position new field will be added; enter a large number to add field to the end.
countMax length of the roiname, including space for terminal null. Function returns NULL (error) in case there is not enough space.

Definition at line 106 of file roiname.c.

118 {
119 if(roiname==NULL) return(roiname);
120 if(field==NULL) return((char*)NULL);
121 unsigned int slen=strlen(roiname);
122 unsigned int flen=strlen(field);
123 if(count < (slen+flen+2)) return((char*)NULL);
124 if(slen==0) {
125 if(flen==0) {strlcpy(roiname, "_", count); return(roiname);}
126 else {strlcpy(roiname, field, count); return(roiname);}
127 }
128
129 char *c, subpart[slen+1], tmp[slen+1];
130 unsigned int i=0;
131 strcpy(tmp, roiname); strcpy(roiname, "");
132 c=roinameSubpart(tmp, " _", i, subpart, slen+1);
133 while(c) {
134 if(i==in) {
135 if(i>0) strlcat(roiname, "_", count);
136 strlcat(roiname, field, count);
137 }
138 if(i>0 || i==in) strlcat(roiname, "_", count);
139 strlcat(roiname, subpart, count);
140 c=roinameSubpart(tmp, " _", ++i, subpart, slen+1);
141 }
142 if(i<=in) {
143 if(i>0) strlcat(roiname, "_", count);
144 strlcat(roiname, field, count);
145 }
146 return(roiname);
147}
char * roinameSubpart(const char *roiname, const char *dlm, const unsigned int si, char *subpart, const unsigned int slen)
Definition roiname.c:20
size_t strlcpy(char *dst, const char *src, size_t dstsize)
Definition stringext.c:632
size_t strlcat(char *dst, const char *src, size_t dstsize)
Definition stringext.c:592

◆ roinameEditByTemplate()

char * roinameEditByTemplate ( const char * template,
const char * currname,
char * newname,
const unsigned int count )
extern

Make a new ROI name based on template and old ROI name.

Returns
Returns pointer to the new ROI name, or NULL in case of an error.
See also
roinameSubpart, roinameAddField, roinameExists, roinameMatch
Parameters
templateTemplate ROI name, where '_' is used to separate sub-parts, and '@' is replaced by the corresponding sub-part from the 'currname'.
currnameCurrent ROI name, from which sub-parts will be added as replacement of '@' in the template. Space character and '_' are assumed to separate the sub-parts.
newnamePointer to pre-allocated string of length count, into which the new ROI name will be written.
countMax length of new name, including terminal null.

Definition at line 65 of file roiname.c.

76 {
77 if(newname==NULL || count<1) return((char*)NULL);
78 newname[0]=(char)0;
79 if(template==NULL || currname==NULL) return((char*)NULL);
80
81 unsigned int i, len;
82 len=strlen(template); i=strlen(currname); if(i>len) len=i;
83 if(len<1) return(newname);
84 char subpart[++len], *c;
85
86 i=0;
87 c=roinameSubpart(template, "_", i, subpart, len);
88 while(c) {
89 /* If not '@' or if '@' can be replaced with sub-part from original tacname, then copy */
90 if(strcmp(subpart, "@")!=0 || roinameSubpart(currname, " _", i, subpart, 256)) {
91 if(i>0) strlcat(newname, "_", count);
92 strlcat(newname, subpart, count);
93 }
94 c=roinameSubpart(template, "_", ++i, subpart, 256);
95 }
96 return(newname);
97}

◆ 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.
See also
roinameSubpart, roinameEditByTemplate, roinameAddField, roinameMatch
Parameters
roinameROI name string; not edited.

Definition at line 158 of file roiname.c.

161 {
162 if(roiname==NULL) return(0);
163 size_t len, n;
164 len=strlen(roiname); if(len==0) return(0);
165 n=strspn(roiname, " _-.\t"); if(n==len) return(0);
166 return(1);
167}

Referenced by tacEnsureNames(), and tacIndividualNames().

◆ roinameMatch()

int roinameMatch ( const char * roiname,
const char * test_str,
TPCSTATUS * status )
extern

Test whether ROI (TAC) name matches with a test string.

Test string can contain wild cards. If both names contain ROI name separators (' ', '_', or '-'), the corresponding sub-names are tested against each other. If test_str does not contain separators but ROI name does, then names are considered matching if test_str matches with any of sub-names.

Returns
1, in case of match, or 0 if not matched.
Author
Vesa Oikonen
See also
roinameSubpart, roinameEditByTemplate, roinameAddField, roinameExists, fnmatch, strstrNoQuotation
Parameters
roinamePointer to ROI name to be tested.
test_strTest string.
statusPointer to status data; enter NULL if not needed.

Definition at line 183 of file roiname.c.

190 {
191 int verbose=0; if(status!=NULL) verbose=status->verbose;
192 if(verbose>0) printf("%s()\n", __func__);
193 statusSet(status, __func__, __FILE__, __LINE__, TPCERROR_OK);
194 /* If both string are empty, then that is a match */
195 if((roiname==NULL || strlen(roiname)<1) && (test_str==NULL || strlen(test_str)<1)) {
196 return(1);
197 }
198 /* If just either of those is empty, then that is a no match */
199 if(roiname==NULL || strlen(roiname)<1) {
200 statusSet(status, __func__, __FILE__, __LINE__, TPCERROR_NO_DATA);
201 return(0);
202 }
203 if(test_str==NULL || strlen(test_str)<1) {
204 statusSet(status, __func__, __FILE__, __LINE__, TPCERROR_NO_DATA);
205 return(0);
206 }
207
208 /* Check the number of name sub-parts */
209 int i, len;
210 len=strlen(roiname); i=strlen(test_str); if(i>len) len=i;
211 char subn1[len+1], subn2[len+1];
212 int roisubnr=0, refsubnr=0;
213 for(i=0; i<6; i++) {
214 if(roinameSubpart(roiname, " _-", i, subn1, len+1)==NULL) break;
215 roisubnr++;
216 }
217 for(i=0; i<6; i++) {
218 if(roinameSubpart(test_str, " _-", i, subn2, len+1)==NULL) break;
219 refsubnr++;
220 }
221 if(verbose>3) printf("roisubnr := %d\nrefsubnr := %d\n", roisubnr, refsubnr);
222 if(roisubnr==0 && refsubnr==0) return(1);
223 if(roisubnr==0 || refsubnr==0) return(0);
224 if(refsubnr>1 && roisubnr!=refsubnr) return(0);
225
226 /* If more than one sub-name to test for, then test against corresponding sub-names with
227 wild cards */
228 if(refsubnr>1) {
229 for(i=0; i<refsubnr; i++) {
230 roinameSubpart(roiname, " _-", i, subn1, len+1);
231 if(!strcmp(subn1, ".")) strcpy(subn1, "");
232 roinameSubpart(test_str, " _-", i, subn2, len+1);
233 if(!strcmp(subn2, ".")) strcpy(subn2, "");
234 if(verbose>3) printf(" '%s' vs '%s'\n", subn1, subn2);
235 if(strnlen(subn1, 1)==0 && strnlen(subn2, 1)==0) continue;
236 if(strnlen(subn2, 1)<1 || fncasematch(subn1, subn2)==0 ) return(0);
237 }
238 return(1);
239 }
240
241 /* So, we have just one sub-name in the test string */
242 /* If it is found in any of sub names, accepting wild cards, then we consider it a match */
243 if(roinameSubpart(test_str, " _-", 0, subn2, len+1)==NULL) return(0);
244 if(!strcmp(subn2, ".")) strcpy(subn2, "");
245 for(i=0; i<roisubnr; i++) {
246 if(roinameSubpart(roiname, " _-", i, subn1, len+1)==NULL) continue;
247 if(!strcmp(subn1, ".")) strcpy(subn1, "");
248 if(fncasematch(subn1, subn2)) return(1);
249 }
250 return(0);
251}
int fncasematch(const char *fname, const char *key)
Definition filename.c:139
void statusSet(TPCSTATUS *s, const char *func, const char *srcfile, int srcline, tpcerror error)
Definition statusmsg.c:142
int verbose
Verbose level, used by statusPrint() etc.

Referenced by parSelectTACs(), and tacSelectTACs().

◆ roinameSubpart()

char * roinameSubpart ( const char * roiname,
const char * dlm,
const unsigned int si,
char * subpart,
const unsigned int slen )
extern

Divide ROI name into its sub-parts, based on user-defined delimiter characters (usually underscore and/or space).

Author
Vesa Oikonen
Returns
Returns pointer to the required sub-part, or NULL if not found.
See also
roinameEditByTemplate, roinameAddField, roinameExists, roinameMatch
Parameters
roinamePointer to ROI name. Not modified.
dlmString containing the sub-part delimiters. For example, " _".
siIndex [0..n-1] of sub-part to search for.
subpartPointer to allocated string for sub-part.
slenLength of the sub-part string, including terminating null. Resulting sub-part length will be at maximum slen-1.

Definition at line 20 of file roiname.c.

32 {
33 if(subpart==NULL || slen<1) return(subpart);
34 subpart[0]=(char)0;
35 if(roiname==NULL || strnlen(roiname, 1)==0) return((char*)NULL);
36 if(dlm==NULL || strnlen(dlm, 1)==0) return((char*)NULL);
37
38 unsigned int i=0;
39 char *s=strdup(roiname);
40 char *sp=s; //printf(" si=%d\n", si);
41 do {
42 //printf(" sp='%s'\n", sp);
43 char *p=strpbrk(sp, dlm);
44 //printf(" i=%d p='%s'\n", i, p);
45 if(!p) {
46 if(si==i) {strlcat(subpart, sp, slen); free(s); return(subpart);}
47 free(s); return((char*)NULL);
48 }
49 *p=(char)0;
50 if(si==i) {strlcat(subpart, sp, slen); free(s); return(subpart);}
51 sp=p+1; i++;
52 } while(*sp);
53
54 if(si==i) {strlcat(subpart, sp, slen); free(s); return(subpart);}
55 free(s);
56 return((char*)NULL);
57}

Referenced by parReadFIT(), parReadRES(), parWriteFIT(), parWriteRES(), roinameAddField(), roinameEditByTemplate(), and roinameMatch().

◆ statusFree()

void statusFree ( TPCSTATUS * s)
extern

After last use, free any memory allocated in the structure.

See also
errorMsg, statusSet, statusInit
Parameters
sPointer to status.

Definition at line 126 of file statusmsg.c.

129 {
130 if(s==NULL) return;
131 free(s->last_file); free(s->last_func);
132 free(s->current_file); free(s->current_func);
133 if(s->fp!=NULL && s->fp!=stdout && s->fp!=stderr) fclose(s->fp);
134 statusInit(s);
135}
void statusInit(TPCSTATUS *s)
Definition statusmsg.c:104
FILE * fp
File pointer for writing log information during development and testing.
char * current_func
Function where status was last time set.
char * last_file
Source file name where status previously set.
char * current_file
Source file name where status was last time set.
char * last_func
Function where status was previously set.

◆ statusInit()

void statusInit ( TPCSTATUS * s)
extern

Before first use, initialize the structure contents using this function. After last use of status structure, call statusFree(), which also calls this function to re-initiate the structure contents.

See also
errorMsg, statusSet, statusFree
Parameters
sPointer to status.

Definition at line 104 of file statusmsg.c.

107 {
108 if(s==NULL) return;
109 s->last_line=0;
110 s->last_file=NULL;
111 s->last_func=NULL;
112 s->current_line=0;
113 s->current_file=NULL;
114 s->current_func=NULL;
115 s->verbose=0;
116 s->fp=stdout;
117 s->forgiving=0;
118 s->error=0;
119}
int forgiving
Force level, 0 for strict tests for data units etc.
int current_line
Source line nr where status was last time set.
int last_line
Source line nr where status was previously set.
tpcerror error
Error code.

Referenced by statusFree().

◆ statusPrint()

void statusPrint ( FILE * fp,
TPCSTATUS * s )
extern

Print the contents of status structure.

Author
Vesa Oikonen
See also
statusSet, errorMsg, statusInit, statusFree
Parameters
fpFile pointer for the output.
sPointer to status.

Definition at line 82 of file statusmsg.c.

87 {
88 if(fp==NULL || s==NULL) return;
89 if(s->current_file!=NULL && s->current_func!=0 && s->current_line>0)
90 fprintf(fp, "In %s() on line %d of file %s\n", s->current_func, s->current_line, s->current_file);
91 if(s->verbose<=0) return;
92 if(s->last_file!=NULL && s->last_func!=0 && s->last_line>0)
93 fprintf(fp, "called in %s() on line %d of file %s\n", s->last_func, s->last_line, s->last_file);
94 return;
95}

◆ statusSet()

void statusSet ( TPCSTATUS * s,
const char * func,
const char * srcfile,
int srcline,
tpcerror error )
extern

Set the status contents.

See also
statusInit, statusFree, errorMsg, tpcProgramName, tpcProcessStdOptions
Parameters
sPointer to status.
funcPointer to function name, usually func.
srcfilePointer to source file name, usually FILE.
srclinePointer to source file line number, usually LINE.
errorError code, 0 if status is ok.

Definition at line 142 of file statusmsg.c.

153 {
154 if(s==NULL) return;
155 s->error=error;
156 /* Delete any previous content */
157 s->last_line=0;
158 free(s->last_file); free(s->last_func);
159 s->last_file=NULL; s->last_func=NULL;
160 /* Move current content to previous */
164 /* Set current contents */
165 s->current_line=srcline;
166 if(func!=NULL) s->current_func=strdup(func);
167 if(srcfile!=NULL) s->current_file=strdup(srcfile);
168 s->error=error;
169}

Referenced by abssWrite(), anaExists(), bfm1TCM(), bfmSRTM(), csvPutLine(), csvPutLineWithSpaces(), csvRead(), csvReorg(), csvWrite(), dcmFileList(), dcmFileRead(), dcmFileRemove(), dcmFileWrite(), dcmMListRead(), dcmmlSortByPlane(), ecatMListRead(), ecatReadMainheader(), ecatWriteMainheader(), iftCopyItems(), iftDeleteDuplicateKeys(), iftPut(), iftPutFromString(), iftPutFromStringWithSpaceSeparator(), iftRead(), iftReplaceKey(), iftReplaceValue(), iftWrite(), iftWriteItem(), imgAllocate(), imgCompareConc(), imgCompareTimes(), imgCompareUnit(), imgFillOHeader(), imgRead(), imgReadDICOM(), imgReadNifti(), imgWrite(), imgWriteDICOM(), imgWriteNifti(), micropetExists(), micropetHeaderRead(), mtgaPlotSVG(), niftiExists(), nlopt1D(), nloptIATGO(), nloptITGO1(), nloptITGO2(), nloptMPSO(), nloptPowellBrent(), nloptSimplex(), nloptSimplexARRS(), parAllocateWithTAC(), parCombineTACs(), parCompareParameterNames(), parCompareParameters(), parCompareParameterUnits(), parCompareTacNames(), parCompareWSS(), parExamplePerfectBolus(), parExampleTTACs(), parFromIFT(), parRead(), parReadCSV(), parReadFIT(), parReadRES(), parSelectByAnother(), parSelectParameters(), parSelectTACs(), parSortByName(), parToIFT(), parWrite(), parWriteCSV(), parWriteFIT(), parWriteIFT(), parWriteRES(), parWriteXML(), roinameMatch(), sifWeight(), spectralDExp(), spectralKRange(), tacAddZeroSample(), tacAllocateWithPAR(), tacAUC(), tacCompareConc(), tacCompareNames(), tacCompareTimes(), tacCompareUnit(), tacCompareWeights(), tacCorrectFrameOverlap(), tacDecayCorrection(), tacDelay(), tacFittime(), tacFormatDetermine(), tacFramesToSteps(), tacGetHeaderInjectiontime(), tacGetHeaderIsotope(), tacGetHeaderScanstarttime(), tacGetHeaderStudynr(), tacGetHeaderTimeunit(), tacGetHeaderUnit(), tacInput2sim(), tacIntegrate(), tacInterpolate(), tacInterpolateInto(), tacInterpolateToEqualLengthFrames(), tacPlotFitSVG(), tacPlotHistogramSVG(), tacPlotLineSVG(), tacRead(), tacRead4DM(), tacReadAllogg(), tacReadCarimasTxt(), tacReadCSV(), tacReadDFT(), tacReadGEMS(), tacReadHRPLUSHC(), tacReadHRRTHC(), tacReadInveonCSV(), tacReadMat(), tacReadModelingData(), tacReadModelingInput(), tacReadOldAllogg(), tacReadPMOD(), tacReadQView(), tacReadReference(), tacReadScanditronics(), tacReadSIF(), tacReadSimple(), tacSelectTACs(), tacSetWeights(), tacSetX(), tacSortByAUC(), tacSortByConc(), tacSortByName(), tacSortByTime(), tacToPAR(), tacVb(), tacVerifyTimeOrder(), tacWByFreq(), tacWeightModerate(), tacWeightNorm(), tacWMove(), tacWrite(), tacWriteCSV(), tacWriteDFT(), tacWritePMOD(), tacWriteSheetIntoXML(), tacWriteSIF(), tacWriteSimple(), tacWriteXML(), tacXUnitConvert(), tacYUnitConvert(), tacYUnitMass2Volume(), and tacYUnitVolume2Mass().

◆ 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.
See also
strdelstr, strstrNoQuotation
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 155 of file stringext.c.

160 {
161 if(!haystack || !*haystack || !needle || !*needle) return 0;
162
163 const char *s=haystack, *p=needle;
164 do {
165 if(!*p) return(char*)haystack;
166 if((*p==*s) || (tolower(*p)==tolower(*s))) {
167 p++; s++;
168 } else {
169 p=needle; if(!*s) return(NULL);
170 s=++haystack;
171 }
172 } while(1);
173 return *p ? NULL : (char*)haystack;
174}

Referenced by csvSearchField(), dcmImgIsotope(), dcmMListRead(), elementIdentify(), iftSearchKey(), iftSearchValue(), imgFormatFromFName(), parFormatFromExtension(), parReadRES(), parWriteRES(), strdelstr(), tacReadInveonCSV(), tacSelectBestReference(), tacWritePMOD(), tacWriteXML(), and unitIdentifyFilename().

◆ strChrCount()

int strChrCount ( const char * s1,
const char * s2 )
extern

Count how many times characters specified in string s2 are found in string s1.

Search is case-sensitive.

Author
Vesa Oikonen
Returns
Returns the nr of characters of s2 found in s1.
See also
strReplaceChar, strstrNoQuotation, strUppercaseCount
Parameters
s1String to search for characters; not modified.
s2String containing characters which are searched for; not modified.

Definition at line 98 of file stringext.c.

103 {
104 unsigned int n=0, i, j;
105 if(s1==NULL || s2==NULL || strlen(s1)==0 || strlen(s2)==0) return (int)n;
106 for(i=0; i<strlen(s1); i++)
107 for(j=0; j<strlen(s2); j++)
108 if(s1[i]==s2[j]) n++;
109 return (int)n;
110}

Referenced by strncpyClean().

◆ strClean()

int strClean ( char * s)
extern

Removes any initial and trailing space characters from specified string s. Removes also quotation marks ("" or '') that may be around the string s. Quotes or space characters in the middle of the string are not removed.

Returns
0 when successful, otherwise >0.
Author
Vesa Oikonen
See also
strncpyCleanSpaces, strCleanSpaces, strIsSpaceOnly, strCleanPars
Parameters
sPointer to the string.

Definition at line 389 of file stringext.c.

392 {
393 if(s==NULL) return 0;
394 int len=strlen(s); if(len<0) return 0;
395 char *s2; s2=calloc(len+1, sizeof(char)); if(s2==NULL) return(1);
396 int n=strncpyClean(s2, s, len+1);
397 if(n<1) strcpy(s, ""); else strcpy(s, s2);
398 free(s2);
399 return 0;
400}
int strncpyClean(char *s1, const char *s2, int maxlen)
Definition stringext.c:321

Referenced by iftPutFromString(), iftPutFromStringWithSpaceSeparator(), imgReadDICOM(), tacNameSplit(), and tacRead4DM().

◆ 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 769 of file stringext.c.

772 {
773 if(s==NULL || *s=='\0') return;
774 strReplaceChar(s, '&', '-');
775 strReplaceChar(s, '\'', '-');
776 strReplaceChar(s, '\"', '-');
777 strReplaceChar(s, '<', '-');
778 strReplaceChar(s, '>', '-');
779 return;
780}
void strReplaceChar(char *s, char c1, char c2)
Definition stringext.c:134

◆ strCleanPars()

void strCleanPars ( char * s)
extern

Remove parenthesis (s), [s], or {s} from around the string s.

Only one set of pars are removed, and only if the same pars are as the first and last character of the string.

Precondition
If necessary, remove possible spaces or quotation marks before this.
See also
strInPars, strCleanSpaces
Author
Vesa Oikonen
Parameters
sPointer to the string.

Definition at line 476 of file stringext.c.

479 {
480 if(s==NULL || strInPars(s)==0) return;
481 int len=strlen(s);
482 s[--len]=(char)0;
483 for(int i=1; i<=len; i++) s[i-1]=s[i];
484 return;
485}
int strInPars(char *s)
Definition stringext.c:453

Referenced by iftGetDoubleWithUnit(), tacRead4DM(), tacReadCarimasTxt(), and tacReadDFT().

◆ 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
See also
strClean, strncpyClean, strncpyCleanSpaces, strIsSpaceOnly
Parameters
sPointer to the string.

Definition at line 300 of file stringext.c.

303 {
304 if(s==NULL) return 0;
305 int len=strlen(s); if(len<0) return 0;
306 char *s2; s2=strdup(s); if(s2==NULL) return(1);
307 int n=strncpyCleanSpaces(s2, s, len+1);
308 if(n<1) strcpy(s, ""); else strcpy(s, s2);
309 free(s2);
310 return 0;
311}
int strncpyCleanSpaces(char *s1, const char *s2, int maxlen)
Definition stringext.c:265

Referenced by csvCleanSpaces(), dcmImgIsotope(), and strncpyClean().

◆ strDateRead()

int strDateRead ( const char * str,
struct tm * date )
extern

Reads date from a standard string representation of date.

Returns
0 when successful, <>0 in case of an error.
See also
strDateTimeRead, strDateTimeValid, ctime_r_int
Author
Vesa Oikonen
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.
datePointer to allocated struct tm where the date is written; undefined if date is not valid.

Definition at line 378 of file datetime.c.

385 {
386 char buf[32];
387 int ret, n, YYYY=0, MM=0, DD=0;
388
389 if(strnlen(str, 10)<8) return 1;
390 if((ret=strDateValid(str))<=0) {
391 strlcpy(buf, str, 11);
392 } else {
393 ret=strDateValid2(str, buf);
394 if(ret>0) ret=strDateValid3(str, buf);
395 }
396 if(ret>0) return 2;
397 n=sscanf(buf, "%d-%d-%d", &YYYY, &MM, &DD);
398 if(n!=3) return(3);
399 date->tm_year=YYYY-1900; date->tm_mday=DD; date->tm_mon=MM-1;
400 date->tm_hour=0; date->tm_min=0; date->tm_sec=0; date->tm_isdst=-1;
401 ret=strftime(buf, 32, "%Y-%m-%d %H:%M:%S", date);
402 if(ret==0) return(4);
403 return(0);
404}
int strDateValid3(const char *str, char *intdate)
Definition datetime.c:214
int strDateValid(const char *str)
Definition datetime.c:155
int strDateValid2(const char *str, char *intdate)
Definition datetime.c:179

Referenced by tacReadGEMS(), and tacReadScanditronics().

◆ strDateTimeAdd()

int strDateTimeAdd ( int s,
char * dt )
extern

Add given time in seconds to the date and time.

Returns
0 if successful.
See also
tmAdd, tmDifference, time_to_tm, strDateTimeDifference
Parameters
sTime to add in seconds; can be negative.
dtPointer to date and time string, edited here. It must be allocated for at least 20 characters.

Definition at line 537 of file datetime.c.

543 {
544 if(dt==NULL) return(1);
545 struct tm tm0;
546 if(strDateTimeRead(dt, &tm0)) return(1);
547 if(s==0) return(0);
548 tmAdd(s, &tm0);
549 if(!strftime(dt, 20, "%Y-%m-%d %H:%M:%S", &tm0)) return(2);
550 return(0);
551}
int strDateTimeRead(const char *str, struct tm *date)
Definition datetime.c:350
void tmAdd(int s, struct tm *d)
Definition datetime.c:500

◆ strDateTimeDifference()

double strDateTimeDifference ( const char * dt1,
const char * dt0 )
extern

Calculate the difference in seconds between two dates and times in international date and time string format (YYYY-MM-DD hh:mm:ss).

See also
tmDifference, strDateTimeAdd, strDateTimeRead, strDateTimeValid, ctime_r_int
Returns
Returns dt1-dt0 time difference in seconds.
Parameters
dt1Pointer to date and time string.
dt0Pointer to date and time string.

Definition at line 519 of file datetime.c.

524 {
525 if(dt1==NULL || dt0==NULL) return(0.0);
526 struct tm tm1, tm0;
527 if(strDateTimeRead(dt1, &tm1) || strDateTimeRead(dt0, &tm0)) return(0.0);
528 return(tmDifference(&tm1, &tm0));
529}
double tmDifference(struct tm *tm1, struct tm *tm0)
Definition datetime.c:486

Referenced by dcmMListRead(), and imgReadDICOM().

◆ strDateTimeRead()

int strDateTimeRead ( const char * str,
struct tm * date )
extern

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

Returns
0 when successful, <>0 in case of an error.
See also
strDateRead, strDateTimeValid, ctime_r_int, tmDifference, strClean
Author
Vesa Oikonen
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
datePointer to allocated struct tm where date and time is written. undefined if date or time is not valid.

Definition at line 350 of file datetime.c.

357 {
358 char buf[32];
359 int ret, n, YYYY=0, MM=0, DD=0, hh=0, mm=0, ss=0;
360
361 ret=strDateTimeValid(str, buf); if(ret!=0) return(ret);
362 n=sscanf(buf, "%d-%d-%d %d:%d:%d", &YYYY, &MM, &DD, &hh, &mm, &ss);
363 if(n!=6) return(40);
364 date->tm_year=YYYY-1900; date->tm_mday=DD; date->tm_mon=MM-1;
365 date->tm_hour=hh; date->tm_min=mm; date->tm_sec=ss; date->tm_isdst=-1;
366 ret=strftime(buf, 32, "%Y-%m-%d %H:%M:%S", date);
367 if(ret==0) return(50);
368 return(0);
369}
int strDateTimeValid(const char *str, char *intdate)
Definition datetime.c:308

Referenced by abssWrite(), strDateTimeAdd(), strDateTimeDifference(), tacReadAllogg(), tacReadGEMS(), and tacReadScanditronics().

◆ strDateTimeValid()

int strDateTimeValid ( const char * str,
char * intdate )
extern

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

Returns
0 if date and time are in correct format, <0 if format is correct but date or time is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
strDateTimeRead, strTimeValid, strDateValid, strClean
Parameters
strString to be verified.
intdatePointer to preallocated string where date and time is written in international format (YYYY-MM-DD hh:mm:ss); enter NULL, if not needed. Undefined, if date is not valid.

Definition at line 308 of file datetime.c.

315 {
316 int ret1, ret2, len;
317 char correct_date[20], *time_ptr=NULL, tmp[20];
318
319 if(str==NULL) return 1;
320 // 1/1/70 00:00:00 or 1970-01-01 00:00:00
321 if(strnlen(str, 19)<15) return 1;
322 /* Separate date and time */
323 len=strcspn(str, " \t");
324 if(len<6 || len>10) return 1;
325 strlcpy(tmp, str, len+1); time_ptr=(char*)str+len+1;
326 /* and check the date */
327 correct_date[0]=(char)0;
328 if((ret1=strDateValid(tmp))<=0) {strlcpy(correct_date, tmp, 20);}
329 else if((ret1=strDateValid2(tmp, correct_date))<=0) {}
330 else if((ret1=strDateValid3(tmp, correct_date))<=0) {}
331 else {return 2;}
332
333 /* the check the time */
334 ret2=strTimeValid(time_ptr);
335 if(ret1>0) {if(ret2>=0) return(100*ret1+ret2); else return(100*ret2);}
336 if(ret2>0) return(10*ret2);
337 if(ret1<0) {if(ret2<0) return(-3); else return(-1);}
338 if(ret2<0) return(-2);
339 if(intdate!=NULL) sprintf(intdate, "%10.10s %8.8s", correct_date, time_ptr);
340 return 0;
341}
int strTimeValid(const char *str)
Definition datetime.c:284

Referenced by dcmDT2intl(), strDateTimeRead(), tacReadOldAllogg(), and tacReadSIF().

◆ strDateValid()

int strDateValid ( const char * str)
extern

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

Returns
0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
ctime_r_int, strDateValid2, strDateValid3, strDateValid4, strDateTimeValid, strClean
Parameters
strString to be verified.

Definition at line 155 of file datetime.c.

158 {
159 if(str==NULL || strnlen(str, 10)<10) return 1;
160 if(str[4]!='-' || str[7]!='-') return 2;
161 if(strncasecmp(str, "YYYY-MM-DD", 10)==0) return -1;
162 int Y, M, D, n;
163 n=sscanf(str, "%4d-%2d-%2d", &Y, &M, &D); if(n!=3) return 3;
164 if(M>12 || D>31) return -1;
165 if(Y<0 || M<1 || D<1) return -1;
166 return 0;
167}

Referenced by dcmDA2intl(), strDateRead(), and strDateTimeValid().

◆ strDateValid2()

int strDateValid2 ( const char * str,
char * intdate )
extern

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

Returns
0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
ctime_r_int, strDateValid, strDateValid3, strDateValid4, strDateTimeValid
Parameters
strString to be verified.
intdatePointer to preallocated string where date is written in international format; enter NULL, if not needed. Undefined, if date is not valid.

Definition at line 179 of file datetime.c.

185 {
186 if(str==NULL || strnlen(str, 10)<8) return 1;
187 int n; char *cptr;
188 cptr=(char*)str; n=strcspn(cptr, "./"); if(n<1 || n>2) return 2;
189 cptr+=n+1; n=strcspn(cptr, "./"); if(n<1 || n>2) return 2;
190 cptr+=n+1; n=strcspn(cptr, "./- \t\n\r"); if(n!=4) return 2;
191 if(strncasecmp(str, "DD.MM.YYYY", 10)==0 || strncasecmp(str, "DD/MM/YYYY", 10)==0) {
192 return -1;
193 }
194 int Y, M, D;
195 n=sscanf(str, "%d/%d/%4d", &D, &M, &Y);
196 if(n<3) n=sscanf(str, "%d.%d.%4d", &D, &M, &Y);
197 if(n!=3) return 3;
198 if(M>12 || D>31) return -1;
199 if(Y<0 || M<1 || D<1) return -1;
200 if(intdate!=NULL) sprintf(intdate, "%04d-%02d-%02d", Y, M, D);
201 return 0;
202}

Referenced by strDateRead(), and strDateTimeValid().

◆ strDateValid3()

int strDateValid3 ( const char * str,
char * intdate )
extern

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

Returns
0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
ctime_r_int, strDateValid2, strDateValid, strDateValid4, strDateTimeValid
Parameters
strString to be verified.
intdatePointer to allocated string where date is written in international format; enter NULL, if not needed. Undefined, if date is not valid.

Definition at line 214 of file datetime.c.

220 {
221 if(str==NULL || strnlen(str, 8)<6) return 1;
222 int n; char *cptr;
223 cptr=(char*)str; n=strcspn(cptr, "./"); if(n<1 || n>2) return 2;
224 cptr+=n+1; n=strcspn(cptr, "./"); if(n<1 || n>2) return 2;
225 cptr+=n+1; n=strcspn(cptr, "./- \t\n\r"); if(n!=2) return 2;
226 if(strncasecmp(str, "DD.MM.YY", 8)==0 || strncasecmp(str, "DD/MM/YY", 8)==0) {
227 return -1;
228 }
229 int Y, M, D;
230 n=sscanf(str, "%d/%d/%2d", &D, &M, &Y);
231 if(n<3) n=sscanf(str, "%d.%d.%2d", &D, &M, &Y);
232 if(n!=3) return 3;
233 if(Y>99 || M>12 || D>31) return -1;
234 if(Y<0 || M<1 || D<1) return -1;
235 if(intdate!=NULL) {
236 if(Y>=70) Y+=1900; else Y+=2000;
237 sprintf(intdate, "%04d-%02d-%02d", Y, M, D);
238 }
239 return 0;
240}

Referenced by strDateRead(), and strDateTimeValid().

◆ strDateValid4()

int strDateValid4 ( int dateint,
char * intdate,
int * year,
int * month,
int * day )
extern

Verify that specified integer contains date in format YYYYMMDD.

Returns
0 if date is in correct format, -1 if format is correct but date is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
ctime_r_int, strDateValid2, strDateValid3, strDateValid, strDateTimeValid
Parameters
dateintInteger to be checked; not changed in this routine.
intdatePointer to allocated string where date is written in international format; enter NULL, if not needed. Undefined, if date is not valid.
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 250 of file datetime.c.

262 {
263 if(dateint<18000101 || dateint>99991231) return 1;
264 int Y, M, D, n;
265 n=dateint/100; D=dateint-100*n; Y=n/100; M=n-100*Y;
266 if(M>12 || D>31) return -1;
267 if(Y<1 || M<1 || D<1) return -1;
268 if(year!=NULL) *year=Y;
269 if(month!=NULL) *month=M;
270 if(day!=NULL) *day=D;
271 if(intdate!=NULL) {sprintf(intdate, "%04d-%02d-%02d", Y, M, D);}
272 return 0;
273}

◆ strdelstr()

char * strdelstr ( char * s1,
const char * s2 )
extern

Find (case-insensitive) s2 in s1, and delete it from s1.

Returns
Returns pointer to s1 at where the deletion stopped, or to the start of s1 in case s2 was not found.
See also
strReplaceChar, strClean, strTrimleft
Parameters
s1Pointer to string in which sub-string s2 is searched; modified.
s2Pointer to sub-string which is searched for in source string s1.

Definition at line 688 of file stringext.c.

693 {
694 if(s1==NULL || s2==NULL) return(s1); //printf("strdelstr('%s', '%s')\n", s1, s2);
695 int n=strlen(s2); if(n<1) return(s1);
696 char *cptr, *rptr;
697 cptr=strcasestr(s1, s2);
698 if(cptr==NULL || *cptr==(char)0) return(s1);
699 rptr=cptr;
700 while(*cptr) {*cptr=cptr[n]; cptr++;}
701 return(rptr);
702}
char * strcasestr(const char *haystack, const char *needle)
Definition stringext.c:155

◆ strdup()

char * strdup ( const char * s)
extern

Allocates memory and copies into it the string addressed by s, including the terminating character.

Postcondition
Remember to free the memory from the returned pointer after last use.
Returns
pointer to allocated string, or NULL in case of error.
Parameters
sString to be duplicated.

Definition at line 185 of file stringext.c.

188 {
189 if(s==NULL) return NULL;
190 size_t length=strlen(s)+1;
191 void *r;
192 r=calloc(length, sizeof(char)); if(r==NULL) return NULL;
193 return (char*)memcpy(r, s, length);
194}

Referenced by atofCheck(), atofVerified(), csvCellReplace(), csvDuplicate(), csvPutString(), dcmFileList(), dcmMListRead(), iftPut(), iftPutFromString(), iftPutFromStringWithSpaceSeparator(), iftReplaceKey(), iftReplaceValue(), parCombineTACs(), parCompareParameterNames(), parCompareTacNames(), parSelectByAnother(), pathCreate(), pathExist(), roinameSubpart(), statusSet(), strCleanSpaces(), strTokenDup(), studynrFromFilename(), tacNameSplit(), tacRead(), tacReadCarimasTxt(), tacReadCSV(), tacReadDFT(), tacReadHRRTHC(), tacReadPMOD(), tpcHtmlUsage(), tpcPrintBuild(), tpcPrintUsage(), and tpcProgramName().

◆ 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
strCleanForXML
Parameters
sPointer to the string to be encoded.

Definition at line 731 of file stringext.c.

734 {
735 if(s==NULL) return(NULL);
736 /* Count the characters needing encoding */
737 int n=0;
738 for(size_t i=0; i<strlen(s); i++) {
739 if(s[i]=='&') {n++; continue;}
740 if(s[i]=='\'') {n++; continue;}
741 if(s[i]=='\"') {n++; continue;}
742 if(s[i]=='<') {n++; continue;}
743 if(s[i]=='>') {n++; continue;}
744 }
745 if(n==0) return(NULL);
746 /* Allocate memory for new string (one char to max 6 chars) */
747 n*=5; n+=strlen(s)+1;
748 char *ns=(char*)malloc(n*sizeof(char));
749 if(ns==NULL) return(NULL);
750 /* Process the string */
751 for(int i=0; i<n; i++) ns[i]=(char)0;
752 for(size_t i=0; i<strlen(s); i++) {
753 if(s[i]=='&') {strcat(ns, "&amp;"); continue;}
754 if(s[i]=='\'') {strcat(ns, "&apos;"); continue;}
755 if(s[i]=='\"') {strcat(ns, "&quot;"); continue;}
756 if(s[i]=='<') {strcat(ns, "&lt;"); continue;}
757 if(s[i]=='>') {strcat(ns, "&gt;"); continue;}
758 ns[strlen(ns)]=s[i];
759 }
760 return(ns);
761}

Referenced by parWriteXML(), and tacWriteXML().

◆ strHaveDecimalComma()

int strHaveDecimalComma ( const char * s)
extern

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

Author
Vesa Oikonen
Returns
1 if decimal comma is found and 0 if not.
See also
strHaveDecimalSeparator, atofVerified, strIsValidNumber
Parameters
sPointer to string.

Definition at line 115 of file decpoint.c.

118 {
119 if(s==NULL) return(0);
120 if(strchr(s, '.')!=NULL) return(0);
121 if(strchr(s, ',')!=NULL) return(1);
122 return(0);
123}

Referenced by tacReadCSV().

◆ strHaveDecimalSeparator()

int strHaveDecimalSeparator ( const char * s)
extern

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

Author
Vesa Oikonen
Returns
0, if neither is found, 1 if dot, and 2 if comma is found.
See also
strHaveDecimalComma, atofVerified, strIsValidNumber
Parameters
sPointer to string.

Definition at line 132 of file decpoint.c.

135 {
136 if(s==NULL) return(0);
137 if(strchr(s, '.')!=NULL) return(1);
138 if(strchr(s, ',')!=NULL) return(2);
139 return(0);
140}

◆ strInPars()

int strInPars ( char * s)
extern

Checks whether string is inside parenthesis (s), [s], or {s}, that is, the same pars as the first and last character of the string.

Precondition
If necessary, remove possible spaces or quotation marks before this.
Returns
0 if not in pars, 1 if inside pars.
Author
Vesa Oikonen
See also
strCleanPars, strCleanSpaces, strIsValidNumber
Parameters
sPointer to the string.

Definition at line 453 of file stringext.c.

456 {
457 if(s==NULL) return 0;
458 int len=strlen(s); if(len<2) return 0;
459 if(s[0]=='(' && s[len-1]==')') return 1;
460 if(s[0]=='{' && s[len-1]=='}') return 1;
461 if(s[0]=='[' && s[len-1]==']') return 1;
462 return 0;
463}

Referenced by strCleanPars(), and tacReadDFT().

◆ strIsSpaceOnly()

int strIsSpaceOnly ( char * s)
extern

Checks whether string contains only space characters.

Text files saved in text editor or Excel may accidentally contain empty looking lines which still may contain tabs and spaces, leading to problems when reading them for example as CSV files.

Returns
0 if lines contains something more than spaces, 1 if only space characters or string is empty.
Author
Vesa Oikonen
See also
strClean, strncpyCleanSpaces
Parameters
sPointer to the string.

Definition at line 671 of file stringext.c.

674 {
675 if(s==NULL) return(1);
676 int len=strlen(s); if(len<1) return(1);
677 for(int i=0; i<len; i++) if(!isspace(s[i])) return(0);
678 return 1;
679}

Referenced by csvRead().

◆ strIsValidNumber()

int strIsValidNumber ( const char * s)
extern

Verifies that given string seems like a valid representation of integer or floating point number in decimal or exponential format.

Returns
1 if string is valid number, and 0 if not.
Author
Vesa Oikonen
See also
atofVerified, atoiCheck, tpcYesNo
Parameters
sPointer to the string to be verified; it must not contain any leading or trailing space characters etc, or it will never verify.

Definition at line 33 of file decpoint.c.

37 {
38 if(s==NULL || strnlen(s, 256)<1) return 0;
39
40 char *p=(char*)s;
41 int i, nn=0;
42 /* It can start with + or minus */
43 if(*p=='+' || *p=='-') p++;
44 /* Then jump over all digits, counting them */
45 i=strspn(p, "0123456789"); nn+=i; p+=i;
46 if(!*p) {if(nn>0) return 1; else return 0;} // end of string
47 /* Then there can be a decimal point or comma, but only one per string */
48 if(*p=='.' || *p==',') p++;
49 if(!*p) {if(nn>0) return 1; else return 0;} // end of string
50 /* Again jump over all digits, counting them */
51 i=strspn(p, "0123456789"); nn+=i; p+=i;
52 /* At this point we must have got at least one digit */
53 if(nn<1) return 0;
54 if(!*p) return 1; // end of string
55 /* String continues, the next character must be E or e */
56 if(*p=='E' || *p=='e') p++; else return 0;
57 /* next can be + or - but not necessarily */
58 if(*p=='+' || *p=='-') p++;
59 /* then we must have at least one digit */
60 i=strspn(p, "0123456789"); if(i<1) return 0;
61 nn+=i; p+=i;
62 /* now we must be at the end of string */
63 if(!*p) return 1; else return 0;
64}

Referenced by atofCheck(), and atofVerified().

◆ 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 592 of file stringext.c.

601 {
602 char *d;
603 const char *s=src;
604 size_t dlen, n;
605
606 /* Find the current length of dst */
607 dlen=strnlen(dst, dstsize);
608 if(s==NULL) return(dlen);
609 n=dstsize-dlen;
610 if(n==0) return(dlen+strlen(s));
611 d=dst+dlen;
612 while(*s!='\0') {
613 if(n!=1) {*d=*s; d++; n--;}
614 s++;
615 }
616 *d='\0';
617 return(dlen+(s-src));
618}

Referenced by fileBackup(), micropetExists(), parReadFIT(), parReadRES(), roinameAddField(), roinameEditByTemplate(), roinameSubpart(), and tpcProgramName().

◆ 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 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 632 of file stringext.c.

641 {
642 if(dstsize>0) dst[0]='\0';
643 if(strlen(src)==0) return(0);
644
645 char *d=dst;
646 const char *s=src;
647 size_t n;
648
649 /* Copy as many chars as allowed */
650 n=dstsize;
651 if(n!=0) while(--n!=0) {*d=*s; if(*d=='\0') {d++; s++; break;} d++; s++;}
652 if(n==0) { // not enough space, add NUL, and check how much space were needed
653 if(dstsize!=0) *d='\0';
654 while(*s++) {}
655 }
656 return(s-src-1);
657}

Referenced by abssWrite(), anaExists(), dcmAddItem(), dcmFileRead(), dcmMListRead(), dcmSameImage(), ecatReadMainheader(), ecatWriteMainheader(), fileBackup(), imgCopyHeader(), imgSetNiftiHeader(), imgWriteNifti(), micropetExists(), niftiCreateFNames(), niftiExists(), parReadCSV(), parReadFIT(), parReadRES(), parWriteFIT(), roinameAddField(), strDateRead(), strDateTimeValid(), strncpyClean(), strncpyCleanSpaces(), strTokenDup(), strTokenNCpy(), studynrFromFilename(), tacGetHeaderIsotope(), tacGetHeaderStudynr(), tacNameSplit(), tacRead4DM(), tacReadCarimasTxt(), tacReadCSV(), tacReadDFT(), tacReadInveonCSV(), tacReadMat(), tacReadOldAllogg(), tacReadPMOD(), tacReadQView(), tacReadSIF(), tacReadSimple(), and tpcProgramName().

◆ strncatDouble()

char * strncatDouble ( char * str1,
const double d,
size_t count )
extern

Concatenate not more than count characters of the string representation of double d to the string pointed to by str1. String is terminated with a null.

See also
strncatInt
Returns
Pointer to str1.
Parameters
str1String to be catenated.
dDouble value to be catenated as string into str1.
countNo more than count characters are concatenated to str1. If str1 was allocated like char str1[MAX_LEN], then set count=MAX_LEN-strlen(str1)-1.

Definition at line 517 of file stringext.c.

526 {
527 char tmp[128]; sprintf(tmp, "%g", d);
528 return strncat(str1, tmp, count);
529}

◆ strncatInt()

char * strncatInt ( char * str1,
const int n,
size_t count )
extern

Concatenate not more than count characters of the string representation of integer n to the string pointed to by str1. String is terminated with a null.

See also
strncatDouble, strncatIntZ, strIsValidNumber
Returns
Pointer to str1.
Parameters
str1String to be catenated.
nInteger value to be catenated as string into str1.
countNo more than count characters are concatenated to str1. If str1 was allocated like char str1[MAX_LEN], then set count=MAX_LEN-strlen(str1)-1.

Definition at line 495 of file stringext.c.

504 {
505 char tmp[128]; sprintf(tmp, "%d", n);
506 return strncat(str1, tmp, count);
507}

◆ strncatIntZ()

char * strncatIntZ ( char * str1,
const int n,
const int maxn,
size_t count )
extern

Concatenate not more than count characters of the zero-padded string representation of integer n to the string pointed to by str1. String is terminated with a null.

See also
strncatInt, strncatDouble
Returns
Pointer to str1.
Parameters
str1String to be catenated.
nInteger value to be catenated as string into str1.
maxnInteger value which is large enough that it would not need to be zero-padded.
countNo more than count characters are concatenated to str1. If str1 was allocated like char str1[MAX_LEN], then set count=MAX_LEN-strlen(str1)-1.

Definition at line 539 of file stringext.c.

550 {
551 if(n<0) strncat(str1, "-", count);
552 char tmp[128]; sprintf(tmp, "%d", abs(maxn));
553 int len=strlen(tmp);
554 sprintf(tmp, "%0*d", len, abs(n));
555 return strncat(str1, tmp, count);
556}

◆ strncpyClean()

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

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

Returns
the length of the new string s1.
Author
Vesa Oikonen
See also
strncpyCleanSpaces, strCleanSpaces, strClean, strIsSpaceOnly, strstrNoQuotation
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 321 of file stringext.c.

329 {
330 if(s1==NULL) return(0);
331 s1[0]=(char)0; if(maxlen<1) return(0);
332 if(maxlen<2) {strcpy(s1, ""); return(0);}
333 if(s2==NULL || strlen(s2)<1) return(0);
334
335 char *tmp;
336 int i, sqn, dqn, m;
337
338 /* Allocate temp string */
339 tmp=calloc(strlen(s2)+1, sizeof(char));
340
341 /* Trim space characters */
342 i=strncpyCleanSpaces(tmp, s2, strlen(s2)+1);
343 if(i<1) {strcpy(s1, ""); free(tmp); return(0);}
344
345 /* Loop as long as there is something to trim */
346 i=1;
347 while(i) {
348 m=0; // nothing modified so far
349 /* Count quotes */
350 sqn=strChrCount(tmp, "\'");
351 dqn=strChrCount(tmp, "\"");
352 if(sqn==0 && dqn==0) {i=0; break;}
353 /* Trim matching quotation marks */
354 if(dqn>=2 && tmp[0]=='\"' && tmp[strlen(tmp)-1]=='\"') {
355 tmp[0]=' '; tmp[strlen(tmp)-1]=(char)0; dqn-=2; m+=2;
356 }
357 if(sqn>=2 && tmp[0]=='\'' && tmp[strlen(tmp)-1]=='\'') {
358 tmp[0]=' '; tmp[strlen(tmp)-1]=(char)0; sqn-=2; m+=2;
359 }
360 /* Trim orphan quotation marks */
361 if(sqn%2) {
362 if(tmp[0]=='\'') {tmp[0]=' '; sqn--; m++;}
363 else if(tmp[strlen(tmp)-1]=='\'') {tmp[strlen(tmp)-1]=(char)0; sqn--; m++;}
364 }
365 if(dqn%2) {
366 if(tmp[0]=='\"') {tmp[0]=' '; dqn--; m++;}
367 else if(tmp[strlen(tmp)-1]=='\"') {tmp[strlen(tmp)-1]=(char)0; dqn--; m++;}
368 }
369 /* If nothing was modified, then do not continue */
370 if(m==0) {i=0; break;}
371 /* Trim spaces, quit if error encountered */
372 if(strCleanSpaces(tmp)) i=0;
373 }
374
375 strlcpy(s1, tmp, maxlen);
376 free(tmp);
377 return(strlen(s1));
378}
int strCleanSpaces(char *s)
Definition stringext.c:300
int strChrCount(const char *s1, const char *s2)
Definition stringext.c:98

Referenced by imgReadDICOM(), parSelectParameters(), parSelectTACs(), strClean(), and tacSelectTACs().

◆ 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
See also
strCleanSpaces, strncpyClean, strIsSpaceOnly
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 265 of file stringext.c.

273 {
274 if(s1==NULL) return(0);
275 s1[0]=(char)0; if(maxlen<1) return(0);
276 if(maxlen<2) {strcpy(s1, ""); return(0);}
277 if(s2==NULL || strlen(s2)<1) return(0);
278
279 char *cptr;
280 int i;
281
282 cptr=(char*)s2; cptr+=strspn(s2, "\t\n\r ");
283 strlcpy(s1, cptr, maxlen); i=strlen(s1); if(i<1) return(0);
284 cptr=s1+(i-1);
285 while(i>0) {
286 if(*cptr!='\t' && *cptr!='\n' && *cptr!='\r' && *cptr!=' ') break;
287 i--; s1[i]=(char)0; cptr--;
288 }
289 return(i);
290}

Referenced by niftiBasename(), parReadFIT(), strCleanSpaces(), strncpyClean(), and tacRead4DM().

◆ strndup()

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

Allocates memory and copies into it first n characters from string addressed by s, and adds the terminating character.

Postcondition
Remember to free the memory from the returned pointer after last use.
Returns
pointer to allocated string, or NULL in case of error.
Parameters
sString to be duplicated.
nMax nr of characters to copy, not including terminal zero.

Definition at line 205 of file stringext.c.

210 {
211 size_t length=strnlen(s, n);
212 void *r; r=calloc(length+1, sizeof(char)); if(r==NULL) return NULL;
213 return (char*)memcpy(r, s, length);
214}

Referenced by csvPutLine(), csvPutLineWithSpaces(), iftPutFromString(), iftPutFromStringWithSpaceSeparator(), and tpcProgramName().

◆ 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, whicever 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 566 of file stringext.c.

572 {
573 if(s==NULL) return(0);
574 char *ps=(char*)s;
575 size_t i=0;
576 while(i<n && *ps!='\0') {i++; ps++;}
577 return(i);
578}

Referenced by abssIdFromFName(), anaExists(), anaReadHeader(), atoiCheck(), dcmAddItem(), dcmDA2intl(), dcmDT2intl(), dcmFileList(), dcmFileRead(), dcmFileRemove(), dcmFileWrite(), dcmSOPIdentify(), dcmSOPUIDName(), dcmTM2intl(), dcmTrUID(), elementIdentify(), fileExist(), filenameGetExtension(), filenameGetExtensions(), filenameRmExtension(), filenameRmExtensions(), filenameRmFile(), filenameRmPath(), imgFormatFromFName(), imgRead(), imgReadDICOM(), imgReadNifti(), imgWrite(), imgWriteDICOM(), imgWriteNifti(), isotopeIdentify(), micropetExists(), micropetHeaderRead(), mtgaPlotSVG(), niftiExists(), niftiReadHeader(), niftiWriteHeader(), parCombineTACs(), parSelectByAnother(), parWriteFIT(), pathCreate(), pathFileList(), pathFileNr(), roinameMatch(), roinameSubpart(), strDateRead(), strDateTimeValid(), strDateValid(), strDateValid2(), strDateValid3(), strIsValidNumber(), strlcat(), strndup(), strTimeValid(), strTokenNr(), studynrFromFilename(), tacPlotFitSVG(), tacPlotHistogramSVG(), tacPlotLineSVG(), tacReadAllogg(), tacReadGEMS(), tacReadMat(), tacReadModelingData(), tacReadModelingInput(), tacReadOldAllogg(), tacReadQView(), tacReadReference(), tacReadScanditronics(), tpcHtmlUsage(), tpcProcessStdOptions(), tpcProgramName(), tpcYesNo(), unitIdentify(), and unitIdentifyFilename().

◆ strReplaceChar()

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

Replace all characters c1 in string s with character c2.

See also
strChrCount, strdelstr, strTrimleft, strstrNoQuotation
Author
Vesa Oikonen
Parameters
sPointer 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 134 of file stringext.c.

141 {
142 char *cptr;
143 if(s==NULL || strlen(s)==0) return;
144 while((cptr=strchr(s, c1))!=NULL) *cptr=c2;
145 return;
146}

Referenced by csvPutDouble(), parCombineTACs(), parCompareParameterNames(), parCompareTacNames(), parSelectByAnother(), parToIFT(), strCleanForXML(), and tacWritePMOD().

◆ strstrNoQuotation()

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

Version of strstr() which ignores any matches inside quotation marks "" or ''.

Returns
a pointer to the beginning of the first occurrence, or NULL if not found.
Author
Vesa Oikonen
Remarks
This function is an enhanced version of the one from libtpcmisc.
See also
strClean, strCleanSpaces
Parameters
haystackPointer to string to be searched.
needlePointer to string with quotation marks.

Definition at line 225 of file stringext.c.

230 {
231 if(haystack==NULL) return((char*)NULL);
232 if(needle==NULL) return((char*)haystack);
233
234 size_t i, test_len;
235 int single_quotation=0;
236 int double_quotation=0;
237 char *cptr;
238
239 test_len=strlen(needle); if(test_len<1) return((char*)haystack);
240 for(i=0, cptr=(char*)haystack; i<strlen(haystack); i++, cptr++) {
241 if(*cptr=='\'') {
242 if(single_quotation==0 && strchr(cptr+1, '\'')!=NULL) single_quotation=1;
243 else single_quotation=0;
244 continue;
245 }
246 if(*cptr=='\"') {
247 if(double_quotation==0 && strchr(cptr+1, '\"')!=NULL) double_quotation=1;
248 else double_quotation=0;
249 continue;
250 }
251 if(single_quotation==1 || double_quotation==1) continue;
252 if(strncmp(cptr, needle, test_len)==0) return(cptr);
253 }
254 return((char*)NULL);
255}

Referenced by csvRead(), iftPutFromString(), and iftPutFromStringWithSpaceSeparator().

◆ strTimeValid()

int strTimeValid ( const char * str)
extern

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

Returns
0 if time is in correct format, -1 if format is correct but time is invalid, and otherwise >0.
Author
Vesa Oikonen
See also
strDateTimeRead, strDateTimeValid, strDateValid
Parameters
strString to be verified.

Definition at line 284 of file datetime.c.

287 {
288 if(str==NULL || strnlen(str, 8)<8) return 1;
289 if(str[2]!=':' || str[5]!=':') return 2;
290 if(strncasecmp(str, "hh:mm:ss", 8)==0) return -1;
291 int h, m, s, n;
292 n=sscanf(str, "%d:%d:%d", &h, &m, &s); if(n!=3) return 3;
293 if(h<0 || h>23 || m<0 || m>59 || s<0 || s>59) return -1;
294 return 0;
295}

Referenced by dcmTM2intl(), iftPutFromString(), and strDateTimeValid().

◆ 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
See also
strTokenNCpy, strstrNoQuotation
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 413 of file stringext.c.

420 {
421 if(next!=NULL) *next=0;
422 if(s1==NULL) return NULL;
423
424 char *s3=NULL, *cptr;
425 size_t j;
426
427 /* If no delimiters, then return copy of s1 */
428 if(s2==NULL || strlen(s2)<1) {
429 s3=strdup(s1); if(next!=NULL) *next=strlen(s1);
430 return s3;
431 }
432 /* Pass initial delimiter characters */
433 cptr=(char*)s1; j=strspn(cptr, s2); cptr+=j; if(next!=NULL) *next=j;
434 /* calculate characters between delimiters */
435 j=strcspn(cptr, s2); if(j==0) {return NULL;}
436 if(next!=NULL) *next+=j;
437 /* Allocate space for token */
438 s3=calloc(j+1, sizeof(char)); if(s3==NULL) return NULL;
439 strlcpy(s3, cptr, j+1);
440 return s3;
441}

Referenced by csvRead(), iftRead(), tacFormatDetermine(), and tacRead4DM().

◆ strTokenNCpy()

int strTokenNCpy ( const char * s1,
const char * s2,
int i,
char * s3,
int count )
extern

Copy the i'th token in the string s1 into string s3. The characters making up the string s2 are the delimiters that determine the tokens.

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

Definition at line 53 of file stringext.c.

64 {
65 int j=0, n=0;
66 char *cptr;
67 if(s3!=NULL && count>0) s3[0]=(char)0;
68 if(s1==NULL || s2==NULL || strlen(s1)==0 || strlen(s2)==0) return(0);
69 if(i<1 || s3==NULL || count<2) return(0);
70
71 cptr=(char*)s1;
72 do {
73 // pass delimiter characters
74 j=strspn(cptr, s2); cptr+=j;
75 // pass characters between delimiters
76 j=strcspn(cptr, s2); if(j>0) n++;
77 // if this is the required token nr, then stop here
78 if(n==i) {
79 if(j>count-1) j=count-1;
80 strlcpy(s3, cptr, j+1); //strncpy(s3, cptr, j); s3[j]=(char)0;
81 break;
82 }
83 cptr+=j;
84 } while(j>0);
85 if(n>i) {s3[0]=(char)0; return(0);}
86 return(j);
87}

Referenced by atofList(), doubleGetWithUnit(), floatGetWithUnit(), iftGetDoubleWithUnit(), intlistAddFromString(), intlistExpandFromString(), parFromIFT(), parReadCSV(), parReadRES(), and tacReadSIF().

◆ strTokenNr()

int strTokenNr ( const char * s1,
const char * s2 )
extern

Calculate the number of tokens in the string s1. The characters making up the string s2 are the delimiters that determine the token.

See also
strTokenNCpy, strTokenDup
Returns
Returns the nr of tokens.
Author
Vesa Oikonen
Parameters
s1String from where tokens are calculated; not modified in any way.
s2String containing character delimiters.

Definition at line 25 of file stringext.c.

30 {
31 int i=0, n=0;
32 char *cptr;
33 if(s1==NULL || s2==NULL || strnlen(s1, 1)==0 || strnlen(s2, 1)==0) return(0);
34
35 cptr=(char*)s1;
36 do {
37 // pass delimiter characters
38 i=strspn(cptr, s2); cptr+=i;
39 // pass characters between delimiters
40 i=strcspn(cptr, s2); cptr+=i; if(i>0) n++;
41 } while(i>0);
42 return(n);
43}

Referenced by atofList(), doubleGetWithUnit(), floatGetWithUnit(), intlistAddFromString(), intlistExpandFromString(), parFromIFT(), parReadRES(), and tacNameSplit().

◆ strTrimLeft()

char * strTrimLeft ( char * s,
const size_t t )
extern

Strip string of t characters from the left.

Returns
Returns pointer to the string.
See also
filenameGetExtension
Parameters
sPointer to the string to be trimmed. Overwritten.
tNumber of characters to remove.

Definition at line 710 of file stringext.c.

715 {
716 if(s==NULL || t==0) return(s);
717 size_t len=strlen(s); if(len<1) return(s);
718 if(t>=len) {s[0]=(char)0; return(s);}
719 memmove(s, s+t, 1+len-t);
720 return(s);
721}

◆ 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 118 of file stringext.c.

121 {
122 unsigned int n=0, i;
123 if(s==NULL || strlen(s)==0) return (int)n;
124 for(i=0; i<strlen(s); i++) if(isupper(s[i])) n++;
125 return (int)n;
126}

◆ studynrFromFilename()

int studynrFromFilename ( const char * fname,
char * studynr,
int force )
extern

Extract study number (max MAX_STUDYNR_LEN chars) from given file name.

If file name string includes path, the path is ignored. This function removes initial zeroes from the numerical part, and converts upper case letters to lower case, if necessary.

Returns
0 if successful.
See also
studynrStandardize, studynrVerify, filenameRmExtensions, filenameRmPath
Parameters
fnameFile name, which may include the path.
studynrPointer for the resulting study number. Memory must be allocated before calling this function (at least MAX_STUDYNR_LEN+1 characters).
forceValidity of studynr is verified (0) or not verified (1).

Definition at line 79 of file studynr.c.

87 {
88 if(studynr==NULL) return(1);
89 strcpy(studynr, "");
90 if(fname==NULL || strnlen(fname, 2)<2) return(1);
91 /* Work with copy of file name */
92 char *temp=strdup(fname);
93 /* Remove path and extensions */
95 /* Check if any part of base file name could be a valid study number */
96 int ret=0, j;
97 size_t i, k, n, len;
98 len=strlen(temp); if(len<1) {free(temp); return(2);}
99 for(i=1; i<len; i++) if(isalpha(temp[i-1]) && isdigit(temp[i])) {
100 j=i-1; while(j>0 && isalpha(temp[j-1])) j--;
101 k=i; while(k<len-1 && isdigit(temp[k+1])) k++;
102 n=k-j+1; if(n>=2 && n<=10) {
103 strlcpy(studynr, temp+j, n+1);
104 if(force==1) {ret=1; break;}
105 if(studynrStandardize(studynr)==0 && studynrVerify(studynr, 0)==0) {
106 ret=2; break;}
107 }
108 }
109 if(ret) {free(temp); return 0;}
110 if(force==0) {free(temp); return 3;}
111 /* ok we have to take something */
112 for(j=0; j<(int)len; j++) if(isalpha(temp[j]) || isdigit(temp[j])) break;
113 for(k=j; k<len-1; k++) if(!isalpha(temp[k+1]) && !isdigit(temp[k+1])) break;
114 n=k-j+1; if(n<1) {free(temp); return 4;}
115 if(n>10) n=10;
116 strlcpy(studynr, temp+j, n+1);
117 free(temp);
118 return 0;
119}
void filenameRmPath(char *s)
Definition filename.c:20
void filenameRmExtensions(char *s)
Definition filename.c:89
int studynrStandardize(char *s)
Definition studynr.c:47
int studynrVerify(const char *s, int zero_ok)
Definition studynr.c:22

Referenced by tacRead().

◆ studynrStandardize()

int studynrStandardize ( char * s)
extern

Remove initial zeroes in the numerical part of the PET study number, and convert any capital letters to lower-case.

Returns
non-zero in case of failure.
See also
studynrVerify, studynrFromFilename
Parameters
sPointer to the study number string to be edited.

Definition at line 47 of file studynr.c.

50 {
51 if(s==NULL) return(1);
52 size_t i, j, len;
53 len=strlen(s); if(len<2) return(1);
54 if(isdigit((int)s[0])) return(2);
55 if(!isdigit((int)s[len-1])) return(3);
56 /* Convert to lower-case */
57 for(i=0; i<len; i++) {
58 if(isdigit((int)s[i])) break;
59 s[i]=(char)tolower((int)s[i]);
60 }
61 /* Remove initial zeroes */
62 for(i=1; i<len; i++) if(isdigit((int)s[i])) break;
63 for(j=i; j<len; j++) if(s[j]!='0') break;
64 if(i==j) return(0); /* no initial zeroes */
65 for(;j<=len; i++, j++) s[i]=s[j];
66 return(0);
67}

Referenced by studynrFromFilename().

◆ studynrVerify()

int studynrVerify ( const char * s,
int zero_ok )
extern

Check that the argument string is a valid TPC study number containing 1-5 letters (upper or lower case) followed by 1-5 digits.

Author
Vesa Oikonen
Returns
0 if study number is valid, 1 if not valid, or >1 in case of failure.
See also
studynrFromFilename, studynrStandardize
Parameters
sPointer to string to test.
zero_okNumber part of study number may start with zero (1) or may not (0).

Definition at line 22 of file studynr.c.

27 {
28 if(s==NULL) return(2);
29 size_t len, i, j;
30 len=strlen(s); if(len<2 || len>10) return(1);
31 for(i=0; i<len; i++) if(!isalnum((int)s[i])) return(1);
32 for(i=0; i<len; i++) if(!isalpha((int)s[i])) break;
33 if(i<1 || i>5) return(1);
34 if(zero_ok==0 && s[i]=='0') return(1); /* first digit must be >0 */
35 for(j=0; (i+j)<len; j++) if(!isdigit((int)s[i+j])) return(1);
36 if(j<1 || j>5) return(1);
37 return(0);
38}

Referenced by studynrFromFilename().

◆ swabip()

void swabip ( void * buf,
int size )
extern

In-place swab, replaces the non-ANSI function swab(), which may not work if data is overlapping.

See also
swawbip, swawip, swap, endianLittle
Parameters
bufPointer to memory
sizeSize of buf in bytes

Definition at line 115 of file endian.c.

120 {
121 if(buf==NULL) return;
122
123 int i;
124 unsigned char c;
125
126 for(i=1; i<size; i+=2) {
127 c=*((unsigned char *)buf+i);
128 *((unsigned char *)buf+i)=*((unsigned char *)buf+(i-1));
129 *((unsigned char *)buf+(i-1))=c;
130 }
131}

Referenced by anaReadHeader(), dcmFileWrite(), dcmWriteFileTag(), niftiReadHeader(), and niftiWriteHeader().

◆ swap()

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

Swap the specified short int, int, long int, float, or double from little endian to big endian or vice versa.

Arguments are allowed to overlap.

See also
swawbip, swabip, swawip, endianLittle
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 69 of file endian.c.

76 {
77 if(from==NULL || to==NULL) return;
78
79 unsigned char c;
80 unsigned short int s;
81 unsigned long l;
82
83 switch(size) {
84 case 1:
85 *(char *)to=*(char *)from;
86 break;
87 case 2:
88 c=*(unsigned char *)from;
89 *(unsigned char *)to = *((unsigned char *)from+1);
90 *((unsigned char *)to+1) = c;
91 /*swab(from, to, size); // NOT ANSI */
92 break;
93 case 4:
94 s=*(unsigned short *)from;
95 *(unsigned short *)to = *((unsigned short *)from+1);
96 *((unsigned short *)to+1) = s;
97 swap((char*)to, (char*)to, 2);
98 swap((char*)((unsigned short *)to+1), (char*)((unsigned short *)to+1), 2);
99 break;
100 case 8:
101 l=*(unsigned long *)from;
102 *(unsigned long *)to = *((unsigned long *)from+1);
103 *((unsigned long *)to+1) = l;
104 swap((char *)to, (char *)to, 4);
105 swap((char*)((unsigned long *)to+1), (char*)((unsigned long *)to+1), 4);
106 break;
107 }
108}
void swap(void *from, void *to, int size)
Definition endian.c:69

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

◆ swap16ip()

void swap16ip ( void * buf,
unsigned long long size )
extern

In-place big-little endian swapping of an array of 16 bit (2 byte) integers.

See also
swap32ip, swap64ip, endianLittle
Parameters
bufPointer to memory.
sizeNr of 16 bit values in the array.

Definition at line 234 of file endian.c.

239 {
240 if(buf==NULL || size==0) return;
241
242 unsigned long long int i;
243 unsigned char c, *cptr;
244
245 cptr=(unsigned char*)buf;
246 for(i=0; i<size; i++, cptr+=2) {
247 c=cptr[0]; cptr[0]=cptr[1]; cptr[1]=c;
248 }
249}

Referenced by imgReadNifti(), niftiReadHeader(), and niftiWriteHeader().

◆ swap32ip()

void swap32ip ( void * buf,
unsigned long long size )
extern

In-place big-little endian swapping of an array of 32 bit (4 byte) integers or floating point values.

See also
swap16ip, swap64ip, endianLittle
Parameters
bufPointer to memory.
sizeNr of 32 bit values in the array.

Definition at line 210 of file endian.c.

215 {
216 if(buf==NULL || size==0) return;
217
218 unsigned long long int i;
219 unsigned char c, *cptr;
220
221 cptr=(unsigned char*)buf;
222 for(i=0; i<size; i++, cptr+=4) {
223 c=cptr[0]; cptr[0]=cptr[3]; cptr[3]=c;
224 c=cptr[1]; cptr[1]=cptr[2]; cptr[2]=c;
225 }
226}

Referenced by imgReadNifti(), niftiReadHeader(), and niftiWriteHeader().

◆ swap64ip()

void swap64ip ( void * buf,
unsigned long long size )
extern

In-place big-little endian swapping of an array of 64 bit (8 byte) integers or floating point values.

See also
swap32ip, swap16ip, endianLittle
Parameters
bufPointer to memory.
sizeNr of 64 bit values in the array.

Definition at line 184 of file endian.c.

189 {
190 if(buf==NULL || size==0) return;
191
192 unsigned long long int i;
193 unsigned char c, *cptr;
194
195 cptr=(unsigned char*)buf;
196 for(i=0; i<size; i++, cptr+=8) {
197 c=cptr[0]; cptr[0]=cptr[7]; cptr[7]=c;
198 c=cptr[1]; cptr[1]=cptr[6]; cptr[6]=c;
199 c=cptr[2]; cptr[2]=cptr[5]; cptr[5]=c;
200 c=cptr[3]; cptr[3]=cptr[4]; cptr[4]=c;
201 }
202}

Referenced by imgReadNifti(), niftiReadHeader(), and niftiWriteHeader().

◆ swawbip()

void swawbip ( void * buf,
int size )
extern

In-place swab and swaw, switches words and bytes from an array of 4-byte ints or floats.

See also
swawip, swabip, swap, endianLittle
Parameters
bufPointer to memory
sizeSize of buf in bytes

Definition at line 138 of file endian.c.

143 {
144 if(buf==NULL) return;
145
146 int i;
147 unsigned char c, *cptr;
148
149 cptr=(unsigned char*)buf;
150 for(i=0; i<size; i+=4, cptr+=4) {
151 c=cptr[0]; cptr[0]=cptr[3]; cptr[3]=c;
152 c=cptr[1]; cptr[1]=cptr[2]; cptr[2]=c;
153 }
154}

Referenced by anaReadHeader(), ecatMListRead(), niftiReadHeader(), and niftiWriteHeader().

◆ swawip()

void swawip ( void * buf,
int size )
extern

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

See also
swawbip, swabip, swap, endianLittle
Parameters
bufPointer to memory
sizeSize of buf in bytes

Definition at line 161 of file endian.c.

166 {
167 if(buf==NULL) return;
168
169 int i;
170 unsigned short int s, *sptr;
171
172 sptr=(unsigned short int*)buf;
173 for(i=0; i<size; i+=4, sptr+=2) {
174 s=sptr[0]; sptr[0]=sptr[1]; sptr[1]=s;
175 }
176}

◆ 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.

See also
ctime_r_int, tmDifference, tmAdd
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 443 of file datetime.c.

451 {
452 long int days, rem, y, yg;
453 const unsigned short *ip;
454
455 days=totalsecs/86400; rem=totalsecs%86400; rem+=offset;
456 while(rem<0) {rem+=86400; --days;}
457 while(rem>=86400) {rem-=86400; ++days;}
458 result->tm_hour=rem/3600;
459 rem%=3600; result->tm_min=rem/60;
460 result->tm_sec=rem%60;
461
462 /* January 1, 1970 was a Thursday. */
463 result->tm_wday=(4+days)%7;
464 if(result->tm_wday<0) result->tm_wday+=7;
465 y=1970;
466 while(days<0 || days>=(isleapyear(y)?366:365)) {
467 /* Guess a corrected year, assuming 365 days per year. */
468 yg=y+math_div(days, 365);
469 /* Adjust days and y to match the guessed year. */
470 days-=(yg-y)*365 + leaps_between(y, yg);
471 y=yg;
472 }
473 result->tm_year=y-1900; result->tm_yday=days;
474 ip=__mon_yday[isleapyear(y)];
475 for(y=11; days<ip[y]; y--) continue;
476 days-=ip[y]; result->tm_mon=y; result->tm_mday=days+1;
477 result->tm_isdst=-1;
478}

◆ 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 thread-safe in Windows.

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

Definition at line 77 of file datetime.c.

80 {
81#ifdef HAVE_GMTIME_R
82 {
83 time_t temp_lt;
84 struct tm temp_gm;
85 if(!tm) temp_lt=0; else temp_lt=mktime(tm);
86 if(gmtime_r(&temp_lt, &temp_gm)==NULL) return((time_t)-1);
87 return(time_t)(temp_lt + (temp_lt - mktime(&temp_gm)));
88 }
89#endif
90
91#ifdef HAVE_GMTIME_S
92 {
93 time_t temp_lt;
94 struct tm temp_gm;
95 if(!tm) temp_lt=0; else temp_lt=mktime(tm);
96 if(gmtime_s(&temp_gm, &temp_lt)!=0) return(time_t)-1);
97 return(time_t)(temp_lt + (temp_lt - mktime(&temp_gm)));
98 }
99#endif
100
101 time_t temp_lt;
102 struct tm *temp_gm;
103 if(!tm) temp_lt=0; else {tm->tm_isdst=-1; temp_lt=mktime(tm);}
104 temp_gm=gmtime(&temp_lt); if(temp_gm) temp_gm->tm_isdst=-1;
105 return(time_t)(temp_lt + (temp_lt - mktime(temp_gm)));
106}

Referenced by tmAdd().

◆ tmAdd()

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

Add given time in seconds to the date and time.

See also
tmDifference, time_to_tm, strDateTimeAdd, strDateTimeDifference
Parameters
sTime to add in seconds; can be negative.
dPointer to tm structure.

Definition at line 500 of file datetime.c.

505 {
506 if(d==NULL) return;
507 d->tm_sec+=s;
508 //mktime(d); // this automatically normalizes sec to hours etc if necessary
509 timegm(d); // this automatically normalizes sec to hours etc if necessary
510}
time_t timegm(struct tm *tm)
Inverse of gmtime, converting struct tm to time_t.
Definition datetime.c:77

Referenced by abssWrite(), and strDateTimeAdd().

◆ tmDifference()

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

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

See also
strDateTimeDifference, tmAdd, time_to_tm
Returns
Returns tm1-tm0 in seconds.
Parameters
tm1Pointer to tm structure.
tm0Pointer to tm structure.

Definition at line 486 of file datetime.c.

491 {
492 return(difftime(mktime(tm1), mktime(tm0)));
493}

Referenced by strDateTimeDifference().

◆ 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, tpcProgramName, tpcPrintBuild
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 169 of file proginfo.c.

176 {
177 unsigned int len, i, j;
178 char *bprogram, *fname, *cptr, *line;
179 FILE *fp;
180
181 if(program==NULL || text==NULL || strnlen(program, 1)<1) return 1;
182
183 /* Clean program name */
184 bprogram=strdup(program);
185 filenameRmPath(bprogram); filenameRmExtension(bprogram);
186
187 /* Make filename */
188 fname=calloc(strlen(path)+1+strlen(bprogram)+5, sizeof(char));
189 if(fname==NULL) {free(bprogram); return 1;}
190 strcpy(fname, path); len=strlen(fname);
191 if(len>0 && (fname[len-1]=='/' || fname[len-1]=='\\')) fname[len-1]=(char)0;
192 len=strlen(fname); if(len>0) strcat(fname, "/");
193 strcat(fname, bprogram); strcat(fname, ".html");
194
195 //printf("fname := '%s'\n", fname);
196
197 /* Open file for write */
198 fp=stdout;
199
200 /* Write HTML header */
201 len=fprintf(fp, "<!DOCTYPE html>\n");
202 if(len<10) {free(bprogram); free(fname); return 2;}
203 fprintf(fp, "<html lang=\"en-GB\">\n");
204 fprintf(fp, "<head>\n");
205 fprintf(fp, " <meta charset=\"utf-8\">\n");
206 fprintf(fp, " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
207 fprintf(fp, " <title>%s</title>\n", bprogram);
208 fprintf(fp, " <style type=\"text/css\">\n");
209 fprintf(fp, " body {\n");
210 fprintf(fp, " margin-left: 2em;\n");
211 fprintf(fp, " font-family: monospace;\n");
212 fprintf(fp, " font-size: 1em;\n");
213 fprintf(fp, " }\n");
214 fprintf(fp, " h1 {\n");
215 fprintf(fp, " font-size: 1.3em;\n");
216 fprintf(fp, " margin-top: 1em;\n");
217 fprintf(fp, " margin-bottom: 1em;\n");
218 fprintf(fp, " }\n");
219 fprintf(fp, " footer {\n");
220 fprintf(fp, " border:1px solid gray;\n");
221 fprintf(fp, " font-size: 0.8em;\n");
222 fprintf(fp, " }\n");
223 fprintf(fp, " footer p {margin-left: 1em;}\n");
224 fprintf(fp, " </style>\n");
225 fprintf(fp, "</head>\n\n");
226
227 /* Write HTML body */
228 fprintf(fp, "<body>\n");
229
230 /* Write program name, version and copyright as title; */
231 /* replace (c) with html code when necessary */
232 fprintf(fp, "<h1>%s - tpcclib %d.%d.%d ", bprogram, tpcclib_VERSION_MAJOR,
233 tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
234 line=tpcclib_COPYRIGHT; len=strlen(line);
235 for(j=0; j<len; j++) {
236 if(strncasecmp(line+j, "(C)", 3)==0) {fputs("&copy;", fp); j+=2; continue;}
237 fputc(line[j], fp);
238 }
239 fputs("</h1>\n\n", fp);
240
241 /* Print usage */
242 fprintf(fp, "<pre>\n");
243 i=0; while(text[i]!=0) {
244 line=text[i];
245 /* If line contains string 'stdoptions' then print instead of it the
246 description of standard command-line options */
247 if(strstr(line, "stdoptions")) {
248 int j=0;
249 while(tpcstdoptions[j]!=0) fprintf(fp, "%s\n", tpcstdoptions[j++]);
250 i++; continue;
251 }
252
253 /* Process "See also" line: add links to other programs */
254 if(strstr(line, "See also: ")!=NULL) {
255 /* copy until the first ':' */
256 j=0; while(line[j]!='\0') {
257 fputc(line[j], fp);
258 j++; if(line[j-1]==':') break;
259 }
260 /* the rest of line with token */
261 char *tline; unsigned int n=0;
262 tline=strdup(line+j); cptr=strtok(tline, ", :;\t\n\r");
263 while(cptr!=NULL) {
264 if(n>0) fputc(',', fp);
265 fprintf(fp, " <a href=\"./%s.html\">%s</a>", cptr, cptr);
266 cptr=strtok(NULL, ", :;\t\n\r");
267 n++;
268 }
269 fputs("\n", fp);
270 free(tline);
271 i++; continue;
272 }
273
274
275 /* Print the line one character at the time */
276 len=strlen(line); j=0;
277 while(j<len) {
278
279 /* If WWW Address follows, then add a link */
280 if(strncasecmp(line+j, "https://", 7)==0) {
281 unsigned int li;
282 cptr=line+j; len=strcspn(cptr, " ),;");
283 fputs("<a href=\"", fp);
284 for(li=0; li<len; li++) fputc(line[j+li], fp);
285 fputs("\">", fp);
286 for(li=0; li<len; li++) fputc(line[j+li], fp);
287 fputs("</a>", fp);
288 j+=len; continue;
289 }
290
291 /* If necessary, replace '@P' with program name */
292 if(strncmp(line+j, " @P ", 4)==0) {
293 fprintf(fp, " %s ", bprogram);
294 j+=4; continue;
295 }
296 /* Replace (c) or (C) with html code */
297 if(strncasecmp(line+j, "(C)", 3)==0) {
298 fputs("&copy;", fp);
299 j+=3; continue;
300 }
301
302 /* Replace <, >, and & characters with html codes */
303 if(line[j]=='<') {fputs("&lt;", fp); j++; continue;}
304 if(line[j]=='>') {fputs("&gt;", fp); j++; continue;}
305 if(line[j]=='&') {fputs("&amp;", fp); j++; continue;}
306
307 /* Just write the char normally */
308 fputc(line[j], fp); j++;
309 }
310 fprintf(fp, "\n");
311 i++; continue;
312
313 }
314 fprintf(fp, "</pre>\n");
315
316 /* Write footer */
317 fprintf(fp, "\n<footer>\n");
318 fprintf(fp, "<p>");
319 i=0; while(tpclicense4html[i]!=0) fprintf(fp, "%s<br>\n", tpclicense4html[i++]);
320 fprintf(fp, "</p>\n");
321 fprintf(fp, "</footer>\n");
322
323 /* Close HTML */
324 fprintf(fp, "</body>\n");
325 fprintf(fp, "</html>\n");
326
327
328 free(bprogram); free(fname);
329 return 0;
330}

◆ tpcPrintBuild()

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

Print tpctools build information.

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

Definition at line 339 of file proginfo.c.

344 {
345 fprintf(fp, "\n");
346 if(program!=NULL) {
347 /* Print program name */
348 char *s; s=strdup(program);
350 fprintf(fp, " Program: %s\n", s);
351 free(s);
352 }
353 /* Build time */
354 fprintf(fp, " Build: %s %s\n",__DATE__,__TIME__);
355 /* tpcclib (and program) version */
356 fprintf(fp, " tpcclib version: %d.%d.%d\n", tpcclib_VERSION_MAJOR,
357 tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
358 /* Compiler information */
359 fprintf(fp, " Build platform: %s\n", tpcclib_BUILD_HOST_SYSTEM_NAME);
360 fprintf(fp, " Build processor: %s\n", tpcclib_BUILD_HOST_SYSTEM_PROCESSOR);
361#if defined(__STDC_VERSION__)
362 fprintf(fp, " Version of C: %ld\n", __STDC_VERSION__);
363#endif
364#if defined(__GNUC__) && defined(__VERSION__)
365 fprintf(fp, " GNU C version: %s\n", __VERSION__);
366#endif
367#if defined(__clang__) && defined(__clang_version__)
368 fprintf(fp, " Clang/LLVM version: %s\n", __clang_version__);
369#endif
370#ifdef _OPENMP
371 fprintf(fp, " OpenMP version: %d\n", _OPENMP);
372#endif
373 /* Platform information */
374#if defined(__x86_64__) || defined(__LP64__) || defined(__ppc64__) || \
375 defined(__LLP64__) || defined(__ILP64__)
376 fprintf(fp, " Architecture: 64-bit\n");
377#else
378 fprintf(fp, " Architecture: 32-bit\n");
379#endif
380 /* Check if IEC 60559 floating-point standard is officially supported;
381 that is 'always' supported, but PET data i/o functions rely on it.
382 GCC does not define __STDC_IEC_559__ or implement the associated standard pragmas. */
383#ifdef __STDC_IEC_559__
384 fprintf(fp, " IEC 60559 floating-point standard is fully supported.\n");
385#endif
386 /* Large File Support extension (LFS) */
387#if defined(_FILE_OFFSET_BITS)
388 fprintf(fp, " _FILE_OFFSET_BITS: %d\n", _FILE_OFFSET_BITS);
389#else
390 fprintf(fp, " _FILE_OFFSET_BITS not defined\n");
391#endif
392#if defined(_LARGEFILE_SOURCE)
393 fprintf(fp, " _LARGEFILE_SOURCE defined\n");
394#endif
395#if defined(_LARGEFILE64_SOURCE)
396 fprintf(fp, " _LARGEFILE64_SOURCE defined\n");
397#endif
398}

◆ 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.
    See also
    tpcHtmlUsage, tpcProgramName, tpcPrintBuild
    Author
    Vesa Oikonen
Parameters
programProgram name.
textProgram usage text.
fpFile pointer where to print; usually stdout.

Definition at line 114 of file proginfo.c.

121 {
122 int i;
123 char *cptr, *bprogram;
124
125 /* Print program name, version, and copyright */
126 if(strlen(program)>0) bprogram=strdup(program);
127 else bprogram=strdup("unknown");
128 filenameRmPath(bprogram); filenameRmExtension(bprogram);
129 fprintf(fp, "\n %s - tpcclib %d.%d.%d %s\n \n", bprogram,
130 tpcclib_VERSION_MAJOR, tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH,
131 tpcclib_COPYRIGHT);
132 /* Print usage */
133 i=0; while(text[i]!=0) {
134 /* If line contains string 'stdoptions' then print instead of it the
135 description of standard command-line options */
136 if(strstr(text[i], "stdoptions")) {
137 int j=0;
138 while(tpcstdoptions[j]!=0) fprintf(fp, " %s\n", tpcstdoptions[j++]);
139 i++; continue;
140 }
141 /* If line does not contain program name, then just print it as it is */
142 cptr=strstr(text[i], " @P ");
143 if(cptr==NULL) {fprintf(fp, " %s\n", text[i++]); continue;}
144 /* Replace '@P' with program name */
145 char *s; s=strdup(text[i]);
146 s[strlen(text[i])-strlen(cptr)]=(char)0;
147 fprintf(fp, " %s %s %s\n", s, bprogram, cptr+4);
148 free(s); i++;
149 }
150 fprintf(fp, " \n");
151 /* Print licence info */
152 i=0; while(tpclicense[i]!=0) fprintf(fp, " %s\n", tpclicense[i++]);
153 fprintf(fp, "\n");
154 free(bprogram);
155}

◆ 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
tpcYesNo, statusSet
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 47 of file proginfo.c.

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

◆ tpcProgramName()

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

Process program name and optionally version into given string, based on user-given string, usually argv[0].

See also
tpcPrintBuild, tpcPrintUsage
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.
nBuffer length of prname, max n-1 characters are written into it, plus nul char.

Definition at line 406 of file proginfo.c.

417 {
418 char *tmp;
419
420 /* Check the input */
421 if(prname==NULL || n<1) return;
422 prname[0]=(char)0;
423
424 /* Remove path and extension */
425 if(strnlen(program, 1024)>0) tmp=strndup(program, 1024);
426 else tmp=strdup("unknown");
428 /* Copy it if possible */
429 n-=strnlen(tmp, 1024); if(n>0) strlcpy(prname, tmp, n);
430 else {free(tmp); return;}
431 free(tmp);
432
433 /* Add version, if required */
434 if(version!=0) {
435 /* Create string with version number */
436 char v[256];
437 sprintf(v, " %d.%d.%d", tpcclib_VERSION_MAJOR, tpcclib_VERSION_MINOR, tpcclib_VERSION_PATCH);
438 /* Copy it if possible */
439 strlcat(prname, v, n);
440 }
441
442 /* Add copyright, if required */
443 if(copyright!=0) {
444 /* Copy it if possible */
445 strlcat(prname, " ", n);
446 strlcat(prname, tpcclib_COPYRIGHT, n);
447 }
448
449 return;
450}
char * strndup(const char *s, size_t n)
Definition stringext.c:205

◆ tpcYesNo()

int tpcYesNo ( const char * s)
extern

Check whether argument string is 'y(es)' or 'n(o)', or 'on' or 'off'.

Returns
Returns 0 when argument means no, 0 when it means no, and -1 if neither.
Author
Vesa Oikonen
See also
atofVerified, atofCheck, atoiCheck
Parameters
sString to be tested.

Definition at line 459 of file proginfo.c.

462 {
463 if(s==NULL || strnlen(s, 3)<1) return(-1);
464 if(strncasecmp(s, "YES", 1)==0) return(1);
465 if(strncasecmp(s, "NO", 1)==0) return(0);
466 if(strcasecmp(s, "ON")==0) return(1);
467 if(strcasecmp(s, "OFF")==0) return(0);
468 return(-1);
469}

◆ unitCombination()

int unitCombination ( const int u1,
const int u2,
const int v1,
const int v2 )
extern

Check whether the combination of units is an identifiable combinatorial unit.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if not supported.
See also
unitConversionFactor, unitIsCombinatorial, unitIdentify, unitName
Parameters
u1Unit #1 of dividend
u2Unit #2 of dividend
v1Unit #1 of divider
v2Unit #2 of divider

Definition at line 745 of file units.c.

754 {
755 /* Try if unit table has this combination */
756 int i, n=0;
757 while(strlen(tpc_unit[n].name)>0) n++;
758 for(i=0; i<n; i++) {
759 if(!((u1==tpc_unit[i].u1 && u2==tpc_unit[i].u2) || (u1==tpc_unit[i].u2 && u2==tpc_unit[i].u1)))
760 continue;
761 if(!((v1==tpc_unit[i].v1 && v2==tpc_unit[i].v2) || (v1==tpc_unit[i].v2 && v2==tpc_unit[i].v1)))
762 continue;
763 return i;
764 }
765 return(UNIT_UNKNOWN);
766}

Referenced by unitDividerMassVolumeConversion(), and unitMultiply().

◆ unitConversionFactor()

double unitConversionFactor ( const int u1,
const int u2 )
extern

Calculates conversion factor between specified two units, if possible.

Multiply value with factor to get the value in unit2.

Returns
Conversion factor (or NaN, if conversion is not possible).
See also
unitIsCombinatorial, unitIdentify, unitName, unitInverse, unitCombination, unitDividerMassVolumeConversion, unitIsRAConc
Parameters
u1Enum unit 1.
u2Enum unit 2.

Definition at line 487 of file units.c.

492 {
493 //printf("unitConversionFactor(%s, %s)\n", unitName(u1), unitName(u2));
494 double cf=nan("");
495 if(u1==UNIT_UNKNOWN || u2==UNIT_UNKNOWN) return cf;
496 if(u1==u2) return 1.0;
497
498 /* If both are time units, then this is easy */
499 if(unitIsTime(u1) && unitIsTime(u2)) {
500 if(u1==UNIT_MSEC) cf=1.0E-3;
501 else if(u1==UNIT_SEC) cf=1.0;
502 else if(u1==UNIT_MIN) cf=60.0;
503 else if(u1==UNIT_HOUR) cf=3600.0;
504 else if(u1==UNIT_DAY) cf=24.0*36000.0;
505 else if(u1==UNIT_MONTH) cf=30.0*24.0*36000.0;
506 else if(u1==UNIT_YEAR) cf=365.0*30.0*24.0*36000.0;
507 if(u2==UNIT_MSEC) cf/=1.0E-3;
508 else if(u2==UNIT_SEC) cf/=1.0;
509 else if(u2==UNIT_MIN) cf/=60.0;
510 else if(u2==UNIT_HOUR) cf/=3600.0;
511 else if(u2==UNIT_DAY) cf/=24.0*36000.0;
512 else if(u2==UNIT_MONTH) cf/=30.0*24.0*36000.0;
513 else if(u2==UNIT_YEAR) cf/=365.0*30.0*24.0*36000.0;
514 else cf=nan("");
515 return cf;
516 }
517
518 /* If both are distances */
519 if(unitIsDistance(u1) && unitIsDistance(u2)) {
520 if(u1==UNIT_UM) cf=1.0E-6;
521 else if(u1==UNIT_MM) cf=1.0E-3;
522 else if(u1==UNIT_CM) cf=1.0E-2;
523 else if(u1==UNIT_M) cf=1.0;
524 if(u2==UNIT_UM) cf/=1.0E-6;
525 else if(u2==UNIT_MM) cf/=1.0E-3;
526 else if(u2==UNIT_CM) cf/=1.0E-2;
527 else if(u2==UNIT_M) cf/=1.0;
528 else cf=nan("");
529 return cf;
530 }
531
532 /* If both are volumes */
533 if(unitIsVolume(u1) && unitIsVolume(u2)) {
534 if(u1==UNIT_UL) cf=1.0E-6;
535 else if(u1==UNIT_ML) cf=1.0E-3;
536 else if(u1==UNIT_DL) cf=1.0E-1;
537 else if(u1==UNIT_L) cf=1.0;
538 if(u2==UNIT_UL) cf/=1.0E-6;
539 else if(u2==UNIT_ML) cf/=1.0E-3;
540 else if(u2==UNIT_DL) cf/=1.0E-1;
541 else if(u2==UNIT_L) cf/=1.0;
542 else cf=nan("");
543 return cf;
544 }
545
546 /* If both are masses */
547 if(unitIsMass(u1) && unitIsMass(u2)) {
548 if(u1==UNIT_UG) cf=1.0E-6;
549 else if(u1==UNIT_MG) cf=1.0E-3;
550 else if(u1==UNIT_G) cf=1.0;
551 else if(u1==UNIT_100G) cf=1.0E+2;
552 else if(u1==UNIT_KG) cf=1.0E+3;
553 if(u2==UNIT_UG) cf/=1.0E-6;
554 else if(u2==UNIT_MG) cf/=1.0E-3;
555 else if(u2==UNIT_G) cf/=1.0;
556 else if(u2==UNIT_100G) cf/=1.0E+2;
557 else if(u2==UNIT_KG) cf/=1.0E+3;
558 else cf=nan("");
559 return cf;
560 }
561
562 /* If both are moles */
563 if(unitIsMole(u1) && unitIsMole(u2)) {
564 if(u1==UNIT_PMOL) cf=1.0E-12;
565 else if(u1==UNIT_NMOL) cf=1.0E-9;
566 else if(u1==UNIT_UMOL) cf=1.0E-6;
567 else if(u1==UNIT_MMOL) cf=1.0E-3;
568 else if(u1==UNIT_MOL) cf=1.0;
569 if(u2==UNIT_PMOL) cf/=1.0E-12;
570 else if(u2==UNIT_NMOL) cf/=1.0E-9;
571 else if(u2==UNIT_UMOL) cf/=1.0E-6;
572 else if(u2==UNIT_MMOL) cf/=1.0E-3;
573 else if(u2==UNIT_MOL) cf/=1.0;
574 else cf=nan("");
575 return cf;
576 }
577
578 /* If both are radioactivities */
580 if(u1==UNIT_BQ) cf=1.0;
581 else if(u1==UNIT_KBQ) cf=1.0E+3;
582 else if(u1==UNIT_MBQ) cf=1.0E+6;
583 else if(u1==UNIT_GBQ) cf=1.0E+9;
584 else if(u1==UNIT_NCI) cf=37.0;
585 else if(u1==UNIT_UCI) cf=3.7E+4;
586 else if(u1==UNIT_MCI) cf=3.7E+7;
587 else if(u1==UNIT_CI) cf=3.7E+10;
588 if(u2==UNIT_BQ) cf/=1.0;
589 else if(u2==UNIT_KBQ) cf/=1.0E+3;
590 else if(u2==UNIT_MBQ) cf/=1.0E+6;
591 else if(u2==UNIT_GBQ) cf/=1.0E+9;
592 else if(u2==UNIT_NCI) cf/=37.0;
593 else if(u2==UNIT_UCI) cf/=3.7E+4;
594 else if(u2==UNIT_MCI) cf/=3.7E+7;
595 else if(u2==UNIT_CI) cf/=3.7E+10;
596 else cf=nan("");
597 return cf;
598 }
599
600 /* Fraction vs percentage */
601 if(u1==UNIT_PERCENTAGE) {
602 if(u2==UNIT_PERCENTAGE) cf=1.0;
603 else if(u2==UNIT_UNITLESS) cf=0.01;
604 return cf;
605 }
606 if(u2==UNIT_PERCENTAGE) {
607 if(u1==UNIT_PERCENTAGE) cf=1.0;
608 else if(u1==UNIT_UNITLESS) cf=100.0;
609 return cf;
610 }
611
612 /* Counts */
613 if(u1==UNIT_COUNTS) {
614 if(u2==UNIT_COUNTS) cf=1.0;
615 else if(u2==UNIT_KCOUNTS) cf=0.001;
616 return cf;
617 }
618 if(u1==UNIT_KCOUNTS) {
619 if(u2==UNIT_KCOUNTS) cf=1.0;
620 else if(u2==UNIT_COUNTS) cf=1000.0;
621 return cf;
622 }
623
624
625 /* And last, the combination units, recursively */
626 if(!unitIsCombinatorial(u1) || !unitIsCombinatorial(u2)) return cf;
627
628 if(tpc_unit[u1].u1==UNIT_UNITLESS && tpc_unit[u2].u1==UNIT_UNITLESS)
629 cf=1.0;
630 else
631 cf=unitConversionFactor(tpc_unit[u1].u1, tpc_unit[u2].u1);
632 if(!isnan(cf)) {
633 if(tpc_unit[u1].u2!=UNIT_UNITLESS && tpc_unit[u2].u2!=UNIT_UNITLESS)
634 cf*=unitConversionFactor(tpc_unit[u1].u2, tpc_unit[u2].u2);
635 if(!isnan(cf)) {
636 if(tpc_unit[u1].v1!=UNIT_UNITLESS && tpc_unit[u2].v1!=UNIT_UNITLESS)
637 cf/=unitConversionFactor(tpc_unit[u1].v1, tpc_unit[u2].v1);
638 if(!isnan(cf)) {
639 if(tpc_unit[u1].v2!=UNIT_UNITLESS && tpc_unit[u2].v2!=UNIT_UNITLESS)
640 cf/=unitConversionFactor(tpc_unit[u1].v2, tpc_unit[u2].v2);
641 }
642 }
643 }
644
645 return cf;
646}
int unitIsMass(int u)
Definition units.c:402
int unitIsRadioactivity(int u)
Definition units.c:444
double unitConversionFactor(const int u1, const int u2)
Definition units.c:487
int unitIsCombinatorial(int u)
Definition units.c:468
int unitIsDistance(int u)
Definition units.c:339
int unitIsMole(int u)
Definition units.c:423
int unitIsVolume(int u)
Definition units.c:382
int unitIsTime(int u)
Definition units.c:359

Referenced by parReadCSV(), tacDecayCorrection(), tacFittime(), tacXMatch(), tacXUnitConvert(), tacYUnitConvert(), and unitConversionFactor().

◆ unitDividendHasRadioactivity()

int unitDividendHasRadioactivity ( int u)
extern

Check whether the unit has radioactivity in the dividend.

Returns
1 if radioactivity in dividend, otherwise 0.
See also
unitIsRadioactivity, unitIsRAConc
Parameters
uEnum unit

Definition at line 710 of file units.c.

713 {
714 if(unitIsRadioactivity(u)) return(1);
715 if(!unitIsCombinatorial(u)) return(0);
716 if(unitIsRadioactivity(tpc_unit[u].u1) || unitIsRadioactivity(tpc_unit[u].u2)) return(1);
717 return(0);
718}

Referenced by unitIsRAConc().

◆ unitDividerHasMass()

int unitDividerHasMass ( int u)
extern

Check whether the unit has mass in divider.

Returns
1 if mass found in divider, otherwise 0.
See also
unitDividerHasVolume, unitIsMass, unitInverse, unitDividerMassVolumeConversion
Parameters
uEnum unit

Definition at line 694 of file units.c.

697 {
698 if(!unitIsCombinatorial(u)) return 0;
699 if(unitIsMass(tpc_unit[u].v1)) return 1;
700 if(unitIsMass(tpc_unit[u].v2)) return 1;
701 return 0;
702}

Referenced by tacYUnitMass2Volume(), unitDividerMassVolumeConversion(), and unitIsRAConc().

◆ unitDividerHasVolume()

int unitDividerHasVolume ( int u)
extern

Check whether the unit has volume in divider.

Returns
1 if volume found in divider, otherwise 0.
See also
unitIsVolume, unitDividerHasMass, unitInverse, unitDividerMassVolumeConversion
Parameters
uEnum unit

Definition at line 678 of file units.c.

681 {
682 if(!unitIsCombinatorial(u)) return 0;
683 if(unitIsVolume(tpc_unit[u].v1)) return 1;
684 if(unitIsVolume(tpc_unit[u].v2)) return 1;
685 return 0;
686}

Referenced by tacYUnitVolume2Mass(), unitDividerMassVolumeConversion(), and unitIsRAConc().

◆ unitDividerMassVolumeConversion()

int unitDividerMassVolumeConversion ( int u)
extern

Convert unit that has either volume or mass unit in divider to corresponding unit (assuming density of 1 g/mL) with either mass or volume in divider.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if not supported.
See also
unitConversionFactor, unitDividerHasVolume, unitDividerHasMass
Parameters
uUnit (enum)

Definition at line 775 of file units.c.

778 {
779 if(unitDividerHasVolume(u)) {
780 int uo=UNIT_UNKNOWN, uu=UNIT_UNKNOWN, uoo=UNIT_UNKNOWN;
781 if(unitIsVolume(tpc_unit[u].v1)) {uo=tpc_unit[u].v1; uoo=tpc_unit[u].v2;}
782 else if(unitIsVolume(tpc_unit[u].v2)) {uo=tpc_unit[u].v2; uoo=tpc_unit[u].v1;}
783 if(uo==UNIT_ML) uu=UNIT_G;
784 else if(uo==UNIT_DL) uu=UNIT_100G;
785 else if(uo==UNIT_L) uu=UNIT_KG;
786 else if(uo==UNIT_UL) uu=UNIT_MG;
787 if(uu==UNIT_UNKNOWN) return(UNIT_UNKNOWN);
788 return(unitCombination(tpc_unit[u].u1, tpc_unit[u].u2, uoo, uu));
789 } else if(unitDividerHasMass(u)) {
790 int uo=UNIT_UNKNOWN, uu=UNIT_UNKNOWN, uoo=UNIT_UNKNOWN;
791 if(unitIsMass(tpc_unit[u].v1)) {uo=tpc_unit[u].v1; uoo=tpc_unit[u].v2;}
792 else if(unitIsMass(tpc_unit[u].v2)) {uo=tpc_unit[u].v2; uoo=tpc_unit[u].v1;}
793 if(uo==UNIT_G) uu=UNIT_ML;
794 else if(uo==UNIT_100G) uu=UNIT_DL;
795 else if(uo==UNIT_KG) uu=UNIT_L;
796 else if(uo==UNIT_MG) uu=UNIT_UL;
797 if(uu==UNIT_UNKNOWN) return(UNIT_UNKNOWN);
798 return(unitCombination(tpc_unit[u].u1, tpc_unit[u].u2, uoo, uu));
799 }
800 return(UNIT_UNKNOWN);
801}
int unitCombination(const int u1, const int u2, const int v1, const int v2)
Definition units.c:745
int unitDividerHasVolume(int u)
Definition units.c:678
int unitDividerHasMass(int u)
Definition units.c:694

Referenced by tacYUnitMass2Volume(), and tacYUnitVolume2Mass().

◆ unitIdentify()

int unitIdentify ( const char * s)
extern

Identify the unit based on string representation s of the unit.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if not identified.
See also
unitName, unitIdentifyFilename, unitIsTime, unitDividerMassVolumeConversion
Parameters
sUnit as a string.

Definition at line 162 of file units.c.

165 {
166 if(s==NULL || strnlen(s, 1)<1) return UNIT_UNKNOWN;
167 /* Try if string can be found directly in the table */
168 int i, n=0;
169 while(strlen(tpc_unit[n].name)>0) n++;
170 for(i=0; i<n; i++) {
171 if(strcasecmp(tpc_unit[i].name, s)==0) return i;
172 }
173 /* Unit string is not following TPC standard, lets try something else */
174 if( strcasecmp(s, "ms")==0) return UNIT_MSEC;
175 else if(strcasecmp(s, "s")==0) return UNIT_SEC;
176 else if(strcasecmp(s, "second")==0) return UNIT_SEC;
177 else if(strcasecmp(s, "seconds")==0) return UNIT_SEC;
178 else if(strcasecmp(s, "mins")==0) return UNIT_MIN;
179 else if(strcasecmp(s, "minute")==0) return UNIT_MIN;
180 else if(strcasecmp(s, "minutes")==0) return UNIT_MIN;
181 else if(strcasecmp(s, "hours")==0) return UNIT_HOUR;
182 else if(strcasecmp(s, "days")==0) return UNIT_DAY;
183 else if(strcasecmp(s, "months")==0) return UNIT_MONTH;
184 else if(strcasecmp(s, "years")==0) return UNIT_YEAR;
185 else if(strcasecmp(s, "yrs")==0) return UNIT_YEAR;
186 else if(strcasecmp(s, "microm")==0) return UNIT_UM;
187 else if(strcasecmp(s, "millim")==0) return UNIT_MM;
188 else if(strcasecmp(s, "microl")==0) return UNIT_UL;
189 else if(strcasecmp(s, "mm^3")==0) return UNIT_UL;
190 else if(strcasecmp(s, "cc")==0) return UNIT_ML;
191 else if(strcasecmp(s, "liter")==0) return UNIT_L;
192 else if(strcasecmp(s, "microgram")==0) return UNIT_UG;
193 else if(strcasecmp(s, "milligram")==0) return UNIT_MG;
194 else if(strcasecmp(s, "gram")==0) return UNIT_G;
195 else if(strcasecmp(s, "100 g")==0) return UNIT_100G;
196 else if(strcasecmp(s, "kilogram")==0) return UNIT_KG;
197 else if(strcasecmp(s, "micromol")==0) return UNIT_UMOL;
198 else if(strcasecmp(s, "micromoles")==0) return UNIT_UMOL;
199 else if(strcasecmp(s, "millimol")==0) return UNIT_MMOL;
200 else if(strcasecmp(s, "millimoles")==0) return UNIT_MMOL;
201 else if(strcasecmp(s, "mole")==0) return UNIT_MOL;
202 else if(strcasecmp(s, "moles")==0) return UNIT_MOL;
203 else if(strcasecmp(s, "cnts")==0) return UNIT_COUNTS;
204 else if(strcasecmp(s, "kcnts")==0) return UNIT_KCOUNTS;
205 else if(strcasecmp(s, "becquerels")==0) return UNIT_BQ;
206 else if(strcasecmp(s, "kbecquerels")==0) return UNIT_KBQ;
207 else if(strcasecmp(s, "cnts/s")==0) return UNIT_CPS;
208 else if(strcasecmp(s, "counts/s")==0) return UNIT_CPS;
209 else if(strcasecmp(s, "counts/sec")==0) return UNIT_CPS;
210 else if(strcasecmp(s, "ECAT counts/sec")==0) return UNIT_CPS;
211 else if(strcasecmp(s, "kcounts/s")==0) return UNIT_KCPS;
212 else if(strcasecmp(s, "kcounts/sec")==0) return UNIT_KCPS;
213 else if(strcasecmp(s, "counts/min")==0) return UNIT_CPM;
214 else if(strcasecmp(s, "kcounts/min")==0) return UNIT_KCPM;
215 else if(strcasecmp(s, "Bq/cc")==0) return UNIT_BQ_PER_ML;
216 else if(strcasecmp(s, "Bqcc")==0) return UNIT_BQ_PER_ML;
217 else if(strcasecmp(s, "BqmL")==0) return UNIT_BQ_PER_ML;
218 else if(strcasecmp(s, "kBq/cc")==0) return UNIT_KBQ_PER_ML;
219 else if(strcasecmp(s, "kBqcc")==0) return UNIT_KBQ_PER_ML;
220 else if(strcasecmp(s, "kBqmL")==0) return UNIT_KBQ_PER_ML;
221 else if(strcasecmp(s, "MBq/cc")==0) return UNIT_MBQ_PER_ML;
222 else if(strcasecmp(s, "MBqcc")==0) return UNIT_MBQ_PER_ML;
223 else if(strcasecmp(s, "MBqmL")==0) return UNIT_MBQ_PER_ML;
224 else if(strcasecmp(s, "nCi/cc")==0) return UNIT_NCI_PER_ML;
225 else if(strcasecmp(s, "nCicc")==0) return UNIT_NCI_PER_ML;
226 else if(strcasecmp(s, "nCimL")==0) return UNIT_NCI_PER_ML;
227 else if(strcasecmp(s, "uCi/cc")==0) return UNIT_UCI_PER_ML;
228 else if(strcasecmp(s, "uCicc")==0) return UNIT_UCI_PER_ML;
229 else if(strcasecmp(s, "uCimL")==0) return UNIT_UCI_PER_ML;
230 else if(strcasecmp(s, "integral")==0) return UNIT_SEC_KBQ_PER_ML;
231 else if(strcasecmp(s, "percent")==0) return UNIT_PERCENTAGE;
232 else if(strcasecmp(s, "perc")==0) return UNIT_PERCENTAGE;
233 else if(strcasecmp(s, "cc/cc")==0) return UNIT_ML_PER_ML;
234 else if(strcasecmp(s, "mL/cc")==0) return UNIT_ML_PER_ML;
235 else if(strcasecmp(s, "cc/mL")==0) return UNIT_ML_PER_ML;
236 else if(strcasecmp(s, "g/cc")==0) return UNIT_G_PER_ML;
237 else if(strcasecmp(s, "SUV")==0) return UNIT_G_PER_ML;
238 else if(strcasecmp(s, "SUVbw")==0) return UNIT_G_PER_ML;
239 else if(strcasecmp(s, "SUV_bw")==0) return UNIT_G_PER_ML;
240 else if(strcasecmp(s, "cc/g")==0) return UNIT_ML_PER_G;
241 else if(strcasecmp(s, "1/s")==0) return UNIT_PER_SEC;
242 else if(strcasecmp(s, "s-1")==0) return UNIT_PER_SEC;
243 else if(strcasecmp(s, "min-1")==0) return UNIT_PER_MIN;
244 else if(strcasecmp(s, "h-1")==0) return UNIT_PER_HOUR;
245 else if(strcmp(s, "pM")==0) return UNIT_PMOL_PER_L;
246 else if(strcmp(s, "nM")==0) return UNIT_NMOL_PER_L;
247 else if(strcmp(s, "uM")==0) return UNIT_UMOL_PER_L;
248 else if(strcmp(s, "mM")==0) return UNIT_MMOL_PER_L;
249 else if(strcasecmp(s, "mL/(sec*mL)")==0) return UNIT_ML_PER_ML_SEC;
250 else if(strcasecmp(s, "mL/sec/mL")==0) return UNIT_ML_PER_ML_SEC;
251 else if(strcasecmp(s, "mL/mL/sec")==0) return UNIT_ML_PER_ML_SEC;
252 else if(strcasecmp(s, "cc/sec/cc")==0) return UNIT_ML_PER_ML_SEC;
253 else if(strcasecmp(s, "cc/cc/sec")==0) return UNIT_ML_PER_ML_SEC;
254 else if(strcasecmp(s, "mL/(sec*cc)")==0) return UNIT_ML_PER_ML_SEC;
255 else if(strcasecmp(s, "mL/(cc*sec)")==0) return UNIT_ML_PER_ML_SEC;
256 else if(strcasecmp(s, "cc/(cc*sec)")==0) return UNIT_ML_PER_ML_SEC;
257 else if(strcasecmp(s, "mL/(min*mL)")==0) return UNIT_ML_PER_ML_MIN;
258 else if(strcasecmp(s, "mL/min/mL")==0) return UNIT_ML_PER_ML_MIN;
259 else if(strcasecmp(s, "mL/mL/min")==0) return UNIT_ML_PER_ML_MIN;
260 else if(strcasecmp(s, "cc/min/cc")==0) return UNIT_ML_PER_ML_MIN;
261 else if(strcasecmp(s, "cc/cc/min")==0) return UNIT_ML_PER_ML_MIN;
262 else if(strcasecmp(s, "mL/(min*g)")==0) return UNIT_ML_PER_G_MIN;
263 else if(strcasecmp(s, "mL/(min*cc)")==0) return UNIT_ML_PER_ML_MIN;
264 else if(strcasecmp(s, "mL/(cc*min)")==0) return UNIT_ML_PER_ML_MIN;
265 else if(strcasecmp(s, "cc/(cc*min)")==0) return UNIT_ML_PER_ML_MIN;
266 else if(strcasecmp(s, "mL/(min*dL)")==0) return UNIT_ML_PER_DL_MIN;
267 else if(strcasecmp(s, "mL/min/dL")==0) return UNIT_ML_PER_DL_MIN;
268 else if(strcasecmp(s, "mL/dL/min")==0) return UNIT_ML_PER_DL_MIN;
269 else if(strcasecmp(s, "umol/(min*mL)")==0) return UNIT_UMOL_PER_ML_MIN;
270 else if(strcasecmp(s, "umol/(min*dL)")==0) return UNIT_UMOL_PER_DL_MIN;
271 else if(strcasecmp(s, "umol/dL/min)")==0) return UNIT_UMOL_PER_DL_MIN;
272 else if(strcasecmp(s, "umol/(min*g)")==0) return UNIT_UMOL_PER_G_MIN;
273 else if(strcasecmp(s, "umol/(min*100g)")==0) return UNIT_UMOL_PER_100G_MIN;
274 else if(strcasecmp(s, "mmol/(min*mL)")==0) return UNIT_MMOL_PER_ML_MIN;
275 else if(strcasecmp(s, "mmol/(min*dL)")==0) return UNIT_MMOL_PER_DL_MIN;
276 else if(strcasecmp(s, "mmol/dL/min)")==0) return UNIT_MMOL_PER_DL_MIN;
277 else if(strcasecmp(s, "mmol/(min*g)")==0) return UNIT_MMOL_PER_G_MIN;
278 else if(strcasecmp(s, "mmol/(min*100g)")==0) return UNIT_MMOL_PER_100G_MIN;
279 else if(strcasecmp(s, "% ID")==0) return UNIT_PID;
280 else if(strcasecmp(s, "%i.d.")==0) return UNIT_PID;
281 else if(strcasecmp(s, "PID")==0) return UNIT_PID;
282 else if(strcasecmp(s, "% ID/mL")==0) return UNIT_PID_PER_ML;
283 else if(strcasecmp(s, "%i.d./mL")==0) return UNIT_PID_PER_ML;
284 else if(strcasecmp(s, "PID/mL")==0) return UNIT_PID_PER_ML;
285 else if(strcasecmp(s, "%ID/cc")==0) return UNIT_PID_PER_ML;
286 else if(strcasecmp(s, "% ID/cc")==0) return UNIT_PID_PER_ML;
287 else if(strcasecmp(s, "PID/cc")==0) return UNIT_PID_PER_ML;
288 else if(strcasecmp(s, "% ID/L")==0) return UNIT_PID_PER_L;
289 else if(strcasecmp(s, "%i.d./L")==0) return UNIT_PID_PER_L;
290 else if(strcasecmp(s, "PID/L")==0) return UNIT_PID_PER_L;
291 else if(strcasecmp(s, "% ID/g")==0) return UNIT_PID_PER_G;
292 else if(strcasecmp(s, "%i.d./g")==0) return UNIT_PID_PER_G;
293 else if(strcasecmp(s, "PID/g")==0) return UNIT_PID_PER_G;
294 else if(strcasecmp(s, "% ID/kg")==0) return UNIT_PID_PER_KG;
295 else if(strcasecmp(s, "%i.d./kg")==0) return UNIT_PID_PER_KG;
296 else if(strcasecmp(s, "PID/kg")==0) return UNIT_PID_PER_KG;
297 else if(strcasecmp(s, "Hounsfield Unit")==0) return UNIT_HU;
298 else if(strcasecmp(s, "HU")==0) return UNIT_HU;
299 else if(strcasecmp(s, "1/1")==0) return UNIT_UNITLESS;
300
301 return UNIT_UNKNOWN;
302}

Referenced by doubleGetWithUnit(), floatGetWithUnit(), iftGetDoubleWithUnit(), imgGetNiftiHeader(), imgReadDICOM(), parFromIFT(), parReadCSV(), parReadFIT(), parReadRES(), parWriteCSV(), tacAllocateWithPAR(), tacGetHeaderTimeunit(), tacGetHeaderUnit(), tacRead4DM(), tacReadCarimasTxt(), tacReadCSV(), tacReadDFT(), tacReadHRRTHC(), tacReadInveonCSV(), and tacReadPMOD().

◆ unitIdentifyFilename()

int unitIdentifyFilename ( const char * s)
extern

Identify calibration unit based on file name.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if not identified.
See also
unitName, unitIdentify, unitDividerHasVolume, unitIsRAConc
Parameters
sFile name.

Definition at line 311 of file units.c.

314 {
315 if(s==NULL || strnlen(s, 3)<3) return UNIT_UNKNOWN;
316 char *cptr;
317 for(int i=0; i<2; i++) {
318 if(i==0) /* On the first run, look in the extension */
319 {cptr=strrchr((char*)s, '.'); if(cptr==NULL) {cptr=(char*)s; i++;}}
320 else /* Then, look into whole filename */
321 cptr=(char*)s;
322 if(strcasestr(cptr, "KBQ")) return UNIT_KBQ_PER_ML;
323 if(strcasestr(cptr, "MBQ")) return UNIT_MBQ_PER_ML;
324 if(strcasestr(cptr, "BQ")) return UNIT_BQ_PER_ML;
325 if(strcasestr(cptr, "NCI")) return UNIT_NCI_PER_ML;
326 if(strcasestr(cptr, "KCPS")) return UNIT_KCPS;
327 if(strcasestr(cptr, "CPS")) return UNIT_CPS;
328 if(strcasestr(cptr, "SUV")) return UNIT_G_PER_ML;
329 }
330 return UNIT_UNKNOWN;
331}

Referenced by tacRead().

◆ unitInverse()

int unitInverse ( int u)
extern

Inverse of given unit.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if not supported.
See also
unitConversionFactor, unitIsCombinatorial, unitIsTime
Parameters
uUnit (enum)

Definition at line 654 of file units.c.

657 {
658 if(u==UNIT_UNKNOWN) return(UNIT_UNKNOWN);
659 else if(u==UNIT_UNITLESS) return(UNIT_UNITLESS);
660 else if(u==UNIT_SEC) return(UNIT_PER_SEC);
661 else if(u==UNIT_PER_SEC) return(UNIT_SEC);
662 else if(u==UNIT_MIN) return(UNIT_PER_MIN);
663 else if(u==UNIT_PER_MIN) return(UNIT_MIN);
664 else if(u==UNIT_HOUR) return(UNIT_PER_HOUR);
665 else if(u==UNIT_PER_HOUR) return(UNIT_HOUR);
666 else if(u==UNIT_ML_PER_ML) return(UNIT_ML_PER_ML);
667 else if(u==UNIT_G_PER_ML) return(UNIT_ML_PER_G);
668 else if(u==UNIT_ML_PER_G) return(UNIT_G_PER_ML);
669 else return(UNIT_UNKNOWN);
670}

◆ unitIsCombinatorial()

int unitIsCombinatorial ( int u)
extern

Check whether the unit is a combinatorial unit.

Returns
1 if combination unit, otherwise 0.
See also
unitConversionFactor, unitIsRadioactivity, unitIsVolume, unitIsMole, unitCombination
Parameters
uEnum unit

Definition at line 468 of file units.c.

471 {
472 if(u<1 || u>=UNIT_LAST) return 0;
473 if(tpc_unit[u].u2==UNIT_UNITLESS && tpc_unit[u].v1==UNIT_UNITLESS &&
474 tpc_unit[u].v2==UNIT_UNITLESS) return 0;
475 return 1;
476}

Referenced by unitConversionFactor(), unitDividendHasRadioactivity(), unitDividerHasMass(), unitDividerHasVolume(), and unitIsRAConc().

◆ unitIsDistance()

int unitIsDistance ( int u)
extern

Check whether the unit is a unit of distance.

Returns
1 if distance unit, otherwise 0.
See also
unitIsTime, unitIdentify, unitName
Parameters
uEnum unit.

Definition at line 339 of file units.c.

342 {
343 switch(u) {
344 case UNIT_UM:
345 case UNIT_MM:
346 case UNIT_CM:
347 case UNIT_M:
348 return 1;
349 }
350 return 0;
351}

Referenced by tacWriteDFT(), and unitConversionFactor().

◆ unitIsMass()

int unitIsMass ( int u)
extern

Check whether the unit is a unit of mass.

Returns
1 if mass unit, otherwise 0.
See also
unitDividerHasMass, unitIsVolume, unitIsMole
Parameters
uEnum unit.

Definition at line 402 of file units.c.

405 {
406 switch(u) {
407 case UNIT_UG:
408 case UNIT_MG:
409 case UNIT_G:
410 case UNIT_100G:
411 case UNIT_KG:
412 return 1;
413 }
414 return 0;
415}

Referenced by unitConversionFactor(), unitDividerHasMass(), unitDividerMassVolumeConversion(), and unitIsRAConc().

◆ unitIsMole()

int unitIsMole ( int u)
extern

Check whether the unit is a unit of chemical mass.

Returns
1 if mole unit, otherwise 0.
See also
unitIsRadioactivity, unitIsMass
Parameters
uEnum unit.

Definition at line 423 of file units.c.

426 {
427 switch(u) {
428 case UNIT_PMOL:
429 case UNIT_NMOL:
430 case UNIT_UMOL:
431 case UNIT_MMOL:
432 case UNIT_MOL:
433 return 1;
434 }
435 return 0;
436}

Referenced by unitConversionFactor().

◆ unitIsRAConc()

int unitIsRAConc ( int u)
extern

Check whether the unit is a known unit of radioactivity per mass or volume.

Returns
1 if radioactivity concentration unit, otherwise 0.
See also
unitDividendHasRadioactivity, unitDividerHasVolume, unitDividerHasMass
Parameters
uEnum unit

Definition at line 726 of file units.c.

729 {
730 if(!unitIsCombinatorial(u)) return(0);
731 if(!unitDividendHasRadioactivity(u)) return(0);
732 if(!unitDividerHasMass(u) && !unitDividerHasVolume(u)) return(0);
733 if(!unitIsRadioactivity(tpc_unit[u].u1)) return(0);
734 if(!unitIsMass(tpc_unit[u].v1) && !unitIsVolume(tpc_unit[u].v1)) return(0);
735 if(tpc_unit[u].u2!=UNIT_UNITLESS || tpc_unit[u].v2!=UNIT_UNITLESS) return(0);
736 return(1);
737}
int unitDividendHasRadioactivity(int u)
Definition units.c:710

Referenced by tacSetWeights().

◆ unitIsRadioactivity()

int unitIsRadioactivity ( int u)
extern

Check whether the unit is a unit of radioactivity.

Returns
1 if radioactivity unit, otherwise 0.
See also
unitIsRAConc, unitIsMole, unitIsMass
Parameters
uEnum unit

Definition at line 444 of file units.c.

447 {
448 switch(u) {
449 case UNIT_BQ:
450 case UNIT_KBQ:
451 case UNIT_MBQ:
452 case UNIT_GBQ:
453 case UNIT_NCI:
454 case UNIT_UCI:
455 case UNIT_MCI:
456 case UNIT_CI:
457 return 1;
458 }
459 return 0;
460}

Referenced by tacSetWeights(), unitConversionFactor(), unitDividendHasRadioactivity(), and unitIsRAConc().

◆ unitIsTime()

int unitIsTime ( int u)
extern

Check whether the unit is a unit of time.

Returns
1 if time unit, otherwise 0.
See also
unitIsDistance, unitConversionFactor, unitInverse, unitIsRAConc, unitIdentify
Parameters
uEnum unit.

Definition at line 359 of file units.c.

362 {
363 switch(u) {
364 case UNIT_MSEC:
365 case UNIT_SEC:
366 case UNIT_MIN:
367 case UNIT_HOUR:
368 case UNIT_DAY:
369 case UNIT_MONTH:
370 case UNIT_YEAR:
371 return 1;
372 }
373 return 0;
374}

Referenced by bfm1TCM(), parWriteCSV(), tacDecayCorrection(), tacPlotFitSVG(), tacPlotLineSVG(), tacSetWeights(), and unitConversionFactor().

◆ unitIsVolume()

int unitIsVolume ( int u)
extern

Check whether the unit is a unit of volume.

Returns
1 if volume unit, otherwise 0.
See also
unitDividerHasVolume, unitIsMass, unitName
Parameters
uEnum unit.

Definition at line 382 of file units.c.

385 {
386 switch(u) {
387 case UNIT_UL:
388 case UNIT_ML:
389 case UNIT_DL:
390 case UNIT_L:
391 return 1;
392 }
393 return 0;
394}

Referenced by unitConversionFactor(), unitDividerHasVolume(), unitDividerMassVolumeConversion(), and unitIsRAConc().

◆ unitMultiply()

int unitMultiply ( int ua,
int ub )
extern

Multiply two units.

Returns
enum unit, or 0 (enum UNIT_UNKNOWN) if combination is not supported.
See also
unitConversionFactor, unitCombination
Parameters
uaUnit A
ubUnit B

Definition at line 809 of file units.c.

814 {
815 /* Verify validity of input units */
816 if(ua<1 || ub<1) return(UNIT_UNKNOWN);
817 int n=0; while(strlen(tpc_unit[n].name)>0) n++;
818 if(ua>n-1 || ub>n-1) return(UNIT_UNKNOWN);
819
820 /* Collect actual components of units */
821 int u[4], v[4], nu=0, nv=0;
822 for(int i=0; i<4; i++) u[i]=v[i]=UNIT_UNITLESS;
823 if(tpc_unit[ua].u1!=UNIT_UNITLESS) u[nu++]=tpc_unit[ua].u1;
824 if(tpc_unit[ua].u2!=UNIT_UNITLESS) u[nu++]=tpc_unit[ua].u2;
825 if(tpc_unit[ua].v1!=UNIT_UNITLESS) v[nv++]=tpc_unit[ua].v1;
826 if(tpc_unit[ua].v2!=UNIT_UNITLESS) v[nv++]=tpc_unit[ua].v2;
827 if(tpc_unit[ub].u1!=UNIT_UNITLESS) u[nu++]=tpc_unit[ub].u1;
828 if(tpc_unit[ub].u2!=UNIT_UNITLESS) u[nu++]=tpc_unit[ub].u2;
829 if(tpc_unit[ub].v1!=UNIT_UNITLESS) v[nv++]=tpc_unit[ub].v1;
830 if(tpc_unit[ub].v2!=UNIT_UNITLESS) v[nv++]=tpc_unit[ub].v2;
831#if(0)
832 printf("units: (");
833 for(int i=0; i<nu; i++) printf(" %s", unitName(u[i]));
834 printf(" ) / (");
835 for(int j=0; j<nv; j++) printf(" %s", unitName(v[j]));
836 printf(" )\n");
837#endif
838
839 /* Cancel out units if possible */
840 int cn=0;
841 for(int i=0; i<nu; i++) for(int j=0; j<nv; j++) if(u[i]==v[j]) {u[i]=v[i]=UNIT_UNITLESS; cn++;}
842 if(cn>0) {
843#if(0)
844 printf("units after cancelling: (");
845 for(int i=0; i<nu; i++) printf(" %s", unitName(u[i]));
846 printf(" ) / (");
847 for(int j=0; j<nv; j++) printf(" %s", unitName(v[j]));
848 printf(" )\n");
849#endif
850 for(int i=0; i<nu-1; i++) if(u[i]==UNIT_UNITLESS)
851 for(int j=i+1; j<nu; i++) if(u[j]!=UNIT_UNITLESS) {
852 int s=u[i]; u[i]=u[j]; u[j]=s;
853 }
854 for(int i=0; i<nv-1; i++) if(v[i]==UNIT_UNITLESS)
855 for(int j=i+1; j<nv; i++) if(v[j]!=UNIT_UNITLESS) {
856 int s=v[i]; v[i]=v[j]; v[j]=s;
857 }
858 nu-=cn; nv-=cn;
859#if(0)
860 printf("units after removing gaps: (");
861 for(int i=0; i<nu; i++) printf(" %s", unitName(u[i]));
862 printf(" ) / (");
863 for(int j=0; j<nv; j++) printf(" %s", unitName(v[j]));
864 printf(" )\n");
865#endif
866 }
867
868 /* Is the new combination a valid unit? */
869 if(nu>2 || nv>2) return(UNIT_UNKNOWN);
870 return(unitCombination(u[0], u[1], v[0], v[1]));
871}
char * unitName(int unit_code)
Definition units.c:143

◆ unitName()

char * unitName ( int unit_code)
extern

Get the string representation of the unit specified with its unit_code.

Returns
pointer to string representation of the unit, "unknown" if not identified.
See also
unitIdentify, unitIsTime, unitCombination
Parameters
unit_codeunit_code as enum or the index of unit in the table.

Definition at line 143 of file units.c.

146 {
147 int n=0;
148
149 while(strlen(tpc_unit[n].name)>0) n++;
150 if(unit_code<1 || unit_code>n-1)
151 return tpc_unit[UNIT_UNKNOWN].name;
152 else
153 return(tpc_unit[unit_code].name);
154}

Referenced by imgCompareUnit(), imgContents(), imgFillOHeader(), imgReadDICOM(), imgSetNiftiHeader(), parAllocateWithTAC(), parCompareParameterUnits(), parExamplePerfectBolus(), parExampleTTACs(), parToIFT(), parWriteCSV(), parWriteRES(), parWriteXML(), tacCompareUnit(), tacPlotFitSVG(), tacPlotLineSVG(), tacRead(), tacRead4DM(), tacSetHeaderTimeunit(), tacSetHeaderUnit(), tacWriteCSV(), tacWriteDFT(), tacWritePMOD(), tacWriteSheetIntoXML(), tacWriteSimple(), tacWriteXML(), tacXUnitConvert(), tacYUnitConvert(), and unitMultiply().