/*Bsub:	This routine subtracts the image pointed to by sbdata from the
		image pointed to by data. The image is assumed to be size*size
		short integers.

Written by Sandor L. Barna, December 1993.

Arthur Woll added saturation level as parameter.

When pedestal == 0, this used to assume that the data, and therefore the
saturation level, should be divided by two. 

Now, the code uses the passed value of saturated regardless of the value of pedestal 

Data that is less than 0 after subtraction is just mapped to 0.

*/

#include <stdio.h>

void bsub(unsigned short *data,unsigned short *sbdata,int size, 
	  int pedestal, int saturated) 
{
    int i;
    int length, low_end;
    int *i_data, *i_sbdata;
    unsigned short int i2_data[2], i2_sbdata[2];
    
    i_data = (int *)&i2_data[0];
    i_sbdata = (int *)&i2_sbdata[0];
    length=size*size;
    printf("On line: ");
    fflush(stdout);
    *i_data = 1;
    if (i2_data[0] == 0)
	low_end = 1;
    else
	low_end = 0;
    if (pedestal > 0) {
	for (i=0;i<length;i++) {
	    *i_data = 0;
	    i2_data[low_end] = data[i];
	    *i_sbdata = 0;
	    i2_sbdata[low_end] = sbdata[i];
	    if (*i_data != saturated) 
		*i_data = *i_data - *i_sbdata + pedestal;
	    if (*i_data <= 0)
		*i_data = pedestal;
	    data[i] = i2_data[low_end];
	    if (i%(size*100) == 0) {
		printf("%d ",i/size);
		fflush(stdout);
	    }
	}
    }
    else {
	for (i=0;i<length;i++) {
	    if (data[i]!=saturated) 
		data[i] = data[i]<sbdata[i]? 0: data[i]-sbdata[i];
	    if (i%(size*100) == 0) {
		printf("%d ",i/size);
		fflush(stdout);
	    }
	}
    }
    printf("\n");
    return;
}