/*
   By Paisan Tooprakai
   ctos.c -- 21 September 2005
      Transform cartesian coor. to spherical coor. 
         r = sqrt(x^2+y^2+z^2)
         theta = atan(sqrt(x^2+y^2)/z) = acos(z/r)
         phi = atan(y/x)
         vr = vx*sin(\theta)*cos(\phi)+vy*sin(\theta)*sin(\phi)
              +vz*cos(\theta)
         vtheta = vx*cos(\theta)*cos(\phi)+vy*cos(\theta)*sin(\phi)
              -vz*sin(\theta)
         vphi = vy*cos(\phi)-vx*sin(\phi)
    
      input file -> rctos.nmf
      output file -> wctos.nmf

*/

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

main()
{
   int    i, no;   
   int    rfile, wfile;
   char   nfpi[80][25],nfpo[80][25];
   double x, y, z;
   double vx, vy, vz;
   double r, theta, phi;
   double rdot, thetadot, phidot; 
   double vr, vtheta, vphi; 
   FILE   *fpo,*fpw,*fp1,*fopen();

   
   if((fp1=fopen("rctos.nmf","r"))==NULL) {
      printf("Error to open rctos.nmf file.\n");
      exit(1);
   }
   for(rfile=0;;rfile++) { /* Count and read file name for reading. */
      if(feof(fp1)==0) {
         fscanf(fp1,"%s",&nfpi[rfile]);
         printf("%s\n",nfpi[rfile]);
      } else {
         break;
      }
   }
   rfile--;
   close(fp1);

   if((fp1=fopen("wctos.nmf","r"))==NULL) {
      printf("Error to open wctos.nmf file.\n");
      exit(1);
   }
   for(wfile=0;;wfile++) { /* Count and read file name for saving. */
      if(feof(fp1)==0) {
         fscanf(fp1,"%s",&nfpo[wfile]);
         printf("%s\n",nfpo[wfile]);
      } else {
         break;
      }
   }
   wfile--;
   close(fp1);

   if(rfile!=wfile) {  /* Check No. of reading and writting file must be equal. */
      printf("No.%d of files for reading are not equal with No.%d of file for writting.\n",rfile,wfile);
      exit(1);
   }
  
   for(i=0;i<wfile;i++) {
      if((fpo=fopen(nfpi[i],"r"))==NULL) {
         printf("Error open %s file for reading.\n",nfpi[i]);
      }
      if((fpw=fopen(nfpo[i],"w"))==NULL) {
         printf("Error open %s file for writting.\n",nfpo[i]);
      }
      for(;;) {
            fscanf(fpo,"%d %lf %lf %lf %lf %lf %lf",&no,&x,&y,&z,&vx,&vy,&vz);
         if(feof(fpo)==0) {
/* printf("%d %lf %lf %lf %lf %lf %lf\n",no,x,y,z,vx,vy,vz); */

            r = sqrt((x*x)+(y*y)+(z*z));
            theta = acos(z/r);
            phi = atan(y/x);
            vr = (vx*sin(theta)*cos(phi))+(vy*sin(theta)*sin(phi))
                +(vz*cos(theta));
            vtheta = (vx*cos(theta)*cos(phi))+(vy*cos(theta)*sin(phi))
                -(vz*sin(theta));
            vphi = (vy*cos(phi))-(vx*sin(phi));

/* printf("%lf %lf %lf %lf\n",sin(theta),cos(theta),sin(phi),cos(phi)); */

           fprintf(fpw,"%d %lf %lf %lf %lf %lf %lf\n",no,phi,theta,r,vphi,vtheta,vr);
         } else {
            break;
         }
      }
      fclose(fpo);
      fclose(fpw);
   }
printf("i = %d\n",i--);
}

