///////////////PAMELA PACKETS SORT///////////////////////////////////
#include "descript.h"
#include "flag.h"

void  RunHeaderReader(char *buf);
extern long int OBTtimesync;
extern long int Timesync;
extern char MYSQL[80];
extern char database[80];
extern int print_flag;

struct Names
{
 char a[80];                     /*Full name for nnnnn_mmm_xxx_AA.bin*/
 char a_short[80];               /*Short name for nnnnn_mmm_xxx_AA.bin*/
 FILE *fo_a;
};

void sort(char log[], char pam[], char path[], char path3[],
		  char file_init[], int packet_type[]) 

{
 FILE *fo_log, *fo_ql, *fo_work2, *f_temp;

 Names data[NumberPack+1];
 char fno2[80];       /* Out help file mm_nnnnn_work2.dat*/
 char ql[80];
 char tmp[80], tmp1[80], numer[10];
 char arina[80];
 char connection[80];
 char query[500];
 long int orbit, route, count;
// char buffer[10];
 char *packet=new char[Nmax];
 unsigned int type=0;           /*PAMELA packet type*/
 unsigned int error=0;          /*PAMELA packet error flag*/
 int Length=0;                  /*Length of filename*/
 long int counter[NumberPack+1];/*Counter for PAMELA packets in each dat file*/
 unsigned long int adr1=0;      /*First byte of PAMELA packet in _cln2.pam*/
 unsigned long int adr2=0;      /*Last byte of PAMELA packet in _cln2.pam*/
 long int time=0;               /*PAMELA packet time*/
 long int moscowtime=0;         /*moscow time of packets*/
 long int first[NumberPack+1];  /*First byte for PAMELA packets of given type*/
 long int last[NumberPack+1];   /*Last byte for PAMELA packets of given type*/
 long int temp=0;
 long int time_differ=0;
 int flag_time=0;
 int Hex_first[4];
 int Hex_last[4];
 int i=0, j=0, stop=0;
 
 for (i=0;i<4;i++)
 {Hex_first[i]=0;
  Hex_last[i]=0;}

 for (i=0;i<NumberPack+1;i++)
 {counter[i]=0;
  first[i]=0;
  last[i]=0;}

 Length=(int)(strlen(file_init));
 strncat(strcpy(tmp,"\0"),file_init,Length-8);
 strcat(strcpy(tmp1,path),"tmp.dat");
 f_temp=fopen(tmp1,"wb+");

 stringstream oss;

 strcpy(connection,MYSQL);
 strcat(connection,database);
 TSQLServer *sqlServer = TSQLServer::Connect(connection, "pamelaprod", "rawprod");

 for (i=0;i<NumberPack+1;i++)
 {
  if (i==0) {fprintf(f_temp,"%02i",i);}
  else {fprintf(f_temp,"%02X",packet_type[i-1]);}
  fseek(f_temp,0,0);
  fgets(numer,10,f_temp);
  fseek(f_temp,0,0);
/*************Open files /home/pamelaprod/rawreader/level0/nnnnn/xxx_mmm/packets/nnnnn_mmm_xxx_AA.bin*******/
  strncat(strcpy(data[i].a,path3),file_init,Length-8);
  strcat(data[i].a,numer); 
  strcat(data[i].a,".bin");
  //form the 'nnnnn_mmm_xxx_AA.bin'
  for (j=0;j<20;j++) tmp[j]=data[i].a[strlen(data[i].a)-(20-j)];
/*********************Create names nnnnn_mmm_xxx_AA.bin********************/  
  for (j=0;j<20;j++) 
  {data[i].a_short[j]=tmp[j]; data[i].a_short[20]='\0';
   data[i].a[strlen(data[i].a)-(20-j)]=tmp[j];
  } 
 
  data[i].fo_a=fopen(data[i].a,"wb"); 
  if(data[i].fo_a==NULL)
  {cerr<<"can not open _%s.dat file",numer; exit(1);}
  
 }
 fclose(f_temp);
 remove(tmp1);
/**********************OPEN NECESSARY FILES************************/
/******************************************************************/
 ifstream fo_pam;
 fo_pam.open(pam,ios::binary);      //open input file "nnnnn_mmm_xxx_cln2.pam"
 if(fo_pam.good()==0) {cerr<<"can not open pam file"; exit(1);} 

 ofstream fo_arina;
 strcpy(arina,"/home/arina/orientation/");
 strcat(arina,data[28].a_short); 
 if (print_flag>0) cout<<arina<<"\n";
 fo_arina.open(arina,ios::binary);
 if(fo_arina.good()==0) {cerr<<"can not open arina file"; exit(1);} 
 
 fo_log=fopen(log, "rb");      //open input file "nnnnn_mmm_xxx_cln2.log"
 if(fo_log==NULL) {cerr<<"can not open log file"; exit(1);}

 strcpy(fno2,path3);
 strncat(fno2,file_init,strlen(file_init)-8); 
 strcat(fno2,"work2.dat");
 fo_work2=fopen(fno2, "wb");   //open output help file "nnnnn_mmm_xxx_work2.dat"
 if(fo_work2==NULL) {cerr<<"can not open outputfile"; exit(1);}

 strncat(strcpy(ql,path3),file_init,Length-8);
 strcat(ql,"ql.log");
 fo_ql=fopen(ql, "wb");        //open output file "nnnnn_mmm_xxx_ql.log"
 if(fo_ql==NULL) {cerr<<"can not open ql file"; exit(1);}

/******************************************************************/
/******************************************************************/
 while(feof(fo_log)==0) 
 {
//read PAMELA packet information from nnnnn_mmm_xxx_cln2.log
  fscanf(fo_log,"%1c",&type);
  if (feof(fo_log)!=0) break;
  fscanf(fo_log,"%4c",&adr1);
  if (feof(fo_log)!=0) break;
  fscanf(fo_log,"%4c",&adr2);
  if (feof(fo_log)!=0) break;
  fscanf(fo_log,"%1c",&error);
  if (feof(fo_log)!=0) break;
  
  if ( ( (bitset<8>(error).test(7))||(error==0)||
	 ((bitset<8>(error).test(0))&&(!bitset<8>(error).test(1))&&(!bitset<8>(error).test(2))&&
	  (!bitset<8>(error).test(3))&&(!bitset<8>(error).test(4))&&(!bitset<8>(error).test(5))&&
	    (!bitset<8>(error).test(6))) )&&
	   (type>0)&&(type<NumberPack+1) )
  {
/*Place file pointer in nnnnn_mmm_xxx_cln2.pam on packet begin*/
   fo_pam.seekg(adr1-1,ios::beg);
//read PAMELA packet from nnnnn_mmm_xxx_cln2.pam
   fo_pam.read(packet,adr2-adr1+1);
  
   /*OBT of Pamela*/
   time=(long int)(unsigned char)(packet[11])+
   	      256*(long int)(unsigned char)(packet[10])+
          256*256*(long int)(unsigned char)(packet[9])+
      256*256*256*(long int)(unsigned char)(packet[8]);
      
 /* mikhailov     time goes to moscow time 08 12 2004*/ 
    
   moscowtime=time-(OBTtimesync-Timesync);
      
   /*temp is packet number*/
   temp=(long int)(unsigned char)(packet[7])+
   	          256*(long int)(unsigned char)(packet[6])+
          256*256*(long int)(unsigned char)(packet[5]);
   if ((print_flag>0)&&(fmod((float)(temp),(float)(10000.))==0.)&&(temp!=0)) cout<<"sorting "<<temp<<"\n";

   /*unpacking several packets....   mikhailov
   unpackingPamelaPacket(packet,type)*/  
   if( type == 11)
   {
    RunHeaderReader(packet);
    if (flag_time==0) time_differ=Timesync-OBTtimesync;
    flag_time=1;
   }
/*******************Packet with type "type"***********************/
   counter[type]+=1;
   //write PAMELA packet in nnnnn_mmm_xxx_AA.bin	   
   if (type!=4) fwrite(packet,adr2-adr1+1,1,data[type].fo_a);
   //write for ARINA
   if (type==28) fo_arina.write(packet,adr2-adr1+1);
   first[type]=last[type]+1;
   last[type]+=adr2-adr1+1;
   temp=first[type];	
   for (i=0;i<4;i++) Hex_first[i]=0;
   for (i=0;i<4;i++)
   {if (temp/(long int)(pow(256.,3-i))>=1) 
	{Hex_first[3-i]=(int)(temp/(long int)(pow(256.,3-i)));
	 temp=temp-(long int)pow(256.,3-i)*
	 (int)(temp/(long int)(pow(256.,3-i)));}}
   temp=last[type];	
   for (i=0;i<4;i++) Hex_last[i]=0;
   for (i=0;i<4;i++)
   {if (temp/(long int)(pow(256.,3-i))>=1) 
    {Hex_last[3-i]=(int)(temp/(long int)(pow(256.,3-i)));
     temp=temp-(long int)pow(256.,3-i)*
     (int)(temp/(long int)(pow(256.,3-i)));}
   }
   //write information about PAMELA packet in nnnnn_mmm_xxx_ql.log
   if (type!=4)
   {
    fprintf(fo_ql,"%1c",char(type));
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(Hex_first[i]));   
    //   for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(Hex_last[i]));
    fprintf(fo_ql,"%1c",char(error));
    //  for (i=8;i<12;i++) fprintf(fo_ql,"%1c",packet[i]);     //!!!!temporary
 
 
    /* mikhailov     time goes to moscow time*  08 12 2004*/ 
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(time>>((3-i)*8)&0XFF));
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(moscowtime>>((3-i)*8)&0XFF));
    for (i=0;i<3;i++) fprintf(fo_ql,"%1c",packet[i+5]);
    for (i=0;i<15;i++) fprintf(fo_ql,"%1c",char(0XFF));  //added to fill 32 bytes
   }
  }
  else
  {
/*******************Packets with errors***************************/
   char *er_pack=new char [adr2-adr1+1];
   /*Place file pointer in nnnnn_mmm_xxx_cln2.pam on error packet begin*/
   fo_pam.seekg(adr1-1,ios::beg);
   //read PAMELA error packet from nnnnn_mmm_xxx_cln2.pam
   fo_pam.read(er_pack,adr2-adr1+1);
   time=(long int)(unsigned char)(er_pack[11])+
   	          256*(long int)(unsigned char)(er_pack[10])+
          256*256*(long int)(unsigned char)(er_pack[9])+
      256*256*256*(long int)(unsigned char)(er_pack[8]);
   counter[0]+=1;
   //write PAMELA packet in nnnnn_mmm_xxx_00.bin	   
   fwrite(er_pack,adr2-adr1+1,1,data[0].fo_a);
   first[0]=last[0]+1;
   last[0]+=adr2-adr1+1;
   temp=first[0];	
   for (i=0;i<4;i++) Hex_first[i]=0;
   for (i=0;i<4;i++)
   {if (temp/(long int)(pow(256.,3-i))>=1) 
    {Hex_first[3-i]=(int)(temp/(long int)(pow(256.,3-i)));
     temp=temp-(long int)pow(256.,3-i)*
     (int)(temp/(long int)(pow(256.,3-i)));}
   }
   temp=last[0];	
   for (i=0;i<4;i++) Hex_last[i]=0;
   for (i=0;i<4;i++)
   {if (temp/(long int)(pow(256.,3-i))>=1) 
    {Hex_last[3-i]=(int)(temp/(long int)(pow(256.,3-i)));
     temp=temp-(long int)pow(256.,3-i)*
     (int)(temp/(long int)(pow(256.,3-i)));}
   }
   if (type!=4)
   {//write information about PAMELA packet in nnnnn_mmm_xxx_ql.log
    fprintf(fo_ql,"%1c",(char)(type));
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(Hex_first[i]));   
    //  for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(Hex_last[i]));  //temporary
    fprintf(fo_ql,"%1c",char(error));
    //   for (i=8;i<12;i++) fprintf(fo_ql,"%1c",er_pack[i]);
    /* mikhailov     time goes to moscow time 08 12 2004*/ 
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(time>>((3-i)*8)&0XFF));
    for (i=0;i<4;i++) fprintf(fo_ql,"%1c",char(moscowtime>>((3-i)*8)&0XFF));
    for (i=0;i<3;i++) fprintf(fo_ql,"%1c",er_pack[i+5]);
    for (i=0;i<15;i++) fprintf(fo_ql,"%1c",char(0XFF));  //added to fill 32 bytes 
  
    delete [] er_pack;   
   }
  } 
 } 

 for (i=0;i<NumberPack+1;i++)
 fprintf(fo_work2,"Number of packets in %s file = %i\n",data[i].a_short,counter[i]);

 for(i=0;i<5;i++) {tmp1[i]=file_init[i];} tmp1[5]=' ';
 sscanf(tmp1,"%5d",&orbit); 
 
 for(i=6;i<9;i++) {tmp1[i-6]=file_init[i];} tmp1[3]=' ';
 sscanf(tmp1,"%3d",&route);
 
 for(i=10;i<13;i++) {tmp1[i-10]=file_init[i];} tmp1[3]=' ';
 sscanf(tmp1,"%3d",&count);
 
 oss.str("");
 oss << "UPDATE FILES1 set time_dif="<<time_differ<<" where cirquit_n="<<orbit<<" and route_n="<<route<<
        " and counter="<<count;
 if (print_flag>0) cout<<oss.str().c_str()<<" table FILES1\n";
 TSQLResult *res=sqlServer->Query(oss.str().c_str());

// Form the query string to write PAMELA packets number in Packets
 query[0]='\0';
 for(i=0;i<NumberPack;i++)
 {
  sprintf(tmp,"%i",counter[i]);
  strcat(tmp,"','");
  strcat(query,tmp);
 }
 sprintf(tmp,"%i",counter[i]);
 strcat(tmp,"')"); 
 strcat(query,tmp);
 
 oss.str("");  
 oss << "INSERT INTO PACKETS (cirquit_n, route_n, counter, P00, P07, P08, P09, P10, P11, P12, P13, P16, P17, P18, P19, P1A,"
     << " P1B, P1C, P1D, P20, P21, P22, P23, P24, P25, P30, P50, P51, P52, P53, P54, P55, P60, P70, P71, P72, P73, P74,"
     << " P75, P76, P77, P81, P82, P83, P84, P85, P86, P88, P89, P8A, PA1, PAB, PF0, PF1, PF2, PF3, PF4)"
     << " VALUES ('"<< orbit << "','"<< route << "','"<<count<<"','"<<query;
 if (print_flag>0) cout<<oss.str().c_str()<<" table PACKETS\n";      
 TSQLResult *res1=sqlServer->Query(oss.str().c_str());

 fo_pam.close();
 fo_arina.close();
 fclose(fo_log);
 fclose(fo_work2);

 for(i=0;i<NumberPack+1;i++) fclose(data[i].fo_a);
 fclose(fo_ql);
 delete [] packet;
}
