/*************************************************************************
  Program:     readbm.c

  Read annual average LAI to calculate biomass.
 ***************************************************************************
  Written by:  J. Liu       
  Modified for application to China  by:  Gang Mo
  Last update: Nov., 2008
*****************************************************************************/
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include "beps.h"

void readbm(line,lc,xx,rcode)
int long line;		/* Line number */
int short *lc;
struct xvalue xx[]; 
int short *rcode;
{
	FILE *fbm; /* Pointers biomass file */
	char *bm;
	int ptr, size, nitems;
	int bytes=1;		/* Number of bytes for a unsigned int data type */
	int long pix;
	double x00,lai_y;

	bm=(char*)malloc(npixels*sizeof(char));
	
/*	Open biomass file */
	if ((fbm= fopen(biomassf,"rb")) ==NULL) {
          printf("\n Unable to open file<%s>,  exitting program ...\n\n",
							biomassf);
          *rcode = ERROR;
	  return;
     }

/*	*** Read a line of data from the biomass file ***/

/*      Set pointer to start of line data */
       
        ptr=bytes*(line*npixels);

/*      Seek to and Read data from delta row and col files */
        
		fseek(fbm,ptr,0);     
        fread(&bm[0],size=bytes,nitems=npixels,fbm);

	/*	  calculating biomass */
		for (pix=0;pix<npixels;pix++)
		{
			lai_y=bm[pix]*0.1;
			switch(lc[pix])
			{
			case 1: case 2: case 3: case 4: case 5: /* conifer */
			x00=0.9097*lai_y+0.125*lai_y*lai_y;
			xx[pix].x9=0.95*x00;	/* stem	 Biomass   kg/m2  */
			xx[pix].x10=0.45*x00;	/*	root Biomass   kg/m2  */
			xx[pix].x8=0.05*x00;	/* leaf  Biomass   kg/m2  */
	       		break;	

			case 6: case 10: 	/* deciduous or mixed forest */
			x00=1.545*lai_y+0.183*lai_y*lai_y;
			xx[pix].x9=0.94*x00;	/*	 stem	Biomass  kg/m2  */
			xx[pix].x10=exp(0.359)*pow(x00,0.639);	/*	root Biomass   kg/m2  */
			xx[pix].x8=0.05*x00;	/* leaf  Biomass   kg/m2  */
			break;

			case 13:  /* shrub  */
			x00=1.545*lai_y+0.183*lai_y*lai_y;
			xx[pix].x9=0.92*x00;	/*	 stem	Biomass  kg/m2  */
			xx[pix].x10=exp(0.359)*pow(x00,0.639);	/*	root Biomass   kg/m2  */
			xx[pix].x8=0.06*x00;	/* leaf  Biomass   kg/m2  */
			break;

			default:
			xx[pix].x9=0.001;
			xx[pix].x10=0.35*lai_y;	/*	root Biomass   kg/m2  */
			xx[pix].x8=0.07*lai_y;	/* leaf  Biomass   kg/m2  */
			break;
			}   /* end of switch  */

		}
          
/*	    Close input file and memory */
        fclose(fbm);
		free(bm);

		return;
}






