00001
00005 #include <math.h>
00006 #include <limits.h>
00007
00008 #include <bpm/bpm_messages.h>
00009 #include <bpm/bpm_process.h>
00010
00025 int handle_saturation( int *wf, int ns, int imax, int nbits, int threshold, int *iunsat ) {
00026
00027 int i;
00028 double min_value, max_value;
00029
00030 *iunsat = -INT_MAX;
00031
00032 if ( ! wf ) {
00033 bpm_error( "Invalid waveform pointer in handle_saturation(...)",
00034 __FILE__, __LINE__ );
00035 return BPM_FAILURE;
00036 }
00037
00038 if ( imax >= ns ) {
00039 bpm_warning( "Maximum sample >= number of samples in handle_saturation(...)",
00040 __FILE__, __LINE__ );
00041 imax = ns - 1;
00042 }
00043
00044 min_value = threshold;
00045 max_value = (int) pow( 2., nbits ) - threshold;
00046
00047 if ( max_value <= min_value ) {
00048 bpm_error( "Check number of bits in ADC and threshold for handle_saturation(...)",
00049 __FILE__, __LINE__ );
00050 return BPM_FAILURE;
00051 }
00052
00053
00054 for( i = imax; i > 0; --i ) {
00055 if ( ( wf[i] > max_value ) || ( wf[i] < min_value ) ) break;
00056 }
00057
00058
00059 if ( i == ns ) {
00060 bpm_warning( "Last unsaturated sample equal to number of samples in handle_saturation(...)",
00061 __FILE__, __LINE__ );
00062 i--;
00063 }
00064
00065 *iunsat = i + 1;
00066
00067 return BPM_SUCCESS;
00068 }