#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define MAXR 300 
#define MAXTHETA 360


/*
 cc -o render render.c -lm
 render KIWA.vol140.dat

 This little gem of a program reads in KIWA.vol140.dat
 and plots a .ppm image file of the radar data.
 Note the conversion of the (x,y) coordinate to an (r,theta)
 coordinate, and the grabbing of the data value from val(r,theta).
*/  

main(int argc, char *argv[])
{
  FILE *ifp;
  FILE *ofp;
  float val[MAXR][MAXTHETA];
  float x,y,r,th,pi,rad,maxv,v,sc;
  char firstline[200];
  int i,j,n,ri,thi,imax,jmax;
  int red,green,blue;
  int colors[16][3]=
		  {
				  {0,0,0},
				  {0,236,236},
				  {1,160,246},
				  {0,0,246},
				  {0,255,0},
				  {0,200,0},
				  {0,144,0},
				  {255,255,0},
				  {231,192,0},
				  {255,144,0},
				  {255,0,0},
				  {214,0,0},
				  {192,0,0},
				  {255,0,255},
				  {153,85,201},
				  {255,255,255}
		};
  

  imax=500;
  jmax=500;
  maxv=0.;

  pi=4*atan2(1.,1.);
  rad=180./pi;
  
  printf("will try to read %s\n",argv[1]);
  ifp=fopen(argv[1],"r");
  fgets(firstline,200,ifp); /* skip first line by reading it */
  for (ri=0; ri<MAXR; ri++)  {
    for (thi=0; thi<MAXTHETA; thi++)  {
      fscanf(ifp,"%f",&val[ri][thi]);
      if (val[ri][thi]>maxv) maxv=val[ri][thi];
    }
  }
  fclose(ifp);
  printf("The maximum relectivity value is %f\n",maxv);
  
  ofp=fopen("radar.ppm","w");
  /* header for PPM output */
  fprintf(ofp,"P6\n#%s\n",argv[1]);
  fprintf(ofp,"%d %d\n255\n",imax,jmax);
  
  for (j=1; j<=jmax; j++){
    for (i=1; i<=imax; i++){
      x=i;
      y=jmax+1-j;
      x=x-imax/2;
      y=y-jmax/2;
      r=sqrt(x*x+y*y);
      th=atan2(x,y)*rad;
      th=th+360.;
      thi=floor(th);
      thi=thi % 360;
      ri=floor(r);
      if (ri>MAXR-1 || val[ri][thi]<5.){
        red=0;
        green=0;
        blue=0;
      }
      else{
        n=floor(val[ri][thi]/5.);
		if (n>15) n=15;
		red=colors[n][0];
		green=colors[n][1];
		blue=colors[n][2];
      }
      fputc((char)red,ofp);
      fputc((char)green,ofp);
      fputc((char)blue,ofp);
    }
  }
  fclose(ofp);
  system("display radar.ppm");
}
