///////////////PAMELA PACKETS SORT///////////////////////////////////
#include "descript.h"
void  RunHeaderReader(char *buf);
extern long int OBTtimesync;
extern long int Timesync;
struct Names
{
 char a[80];                     /*Full name for mmm_nnnnn_counter_xx.bin*/
 char a_short[80];               /*Short name for mmm_nnnnn_counter_xx.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 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;
 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+");

 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/mmm_counter/packets/mmm_nnnnn_counter_xx.bin*******/
  strncat(strcpy(data[i].a,path3),file_init,Length-8);
  strcat(data[i].a,numer);
  strcat(data[i].a,".bin");
  //form the 'mmm_'
  for (j=0;j<4;j++) tmp[j]=data[i].a[strlen(data[i].a)-(20-j)];
  //form the 'mmm_nnnnn_'
  for (j=0;j<6;j++) tmp[j+4]=data[i].a[strlen(data[i].a)-(12-j)];
  //form the 'mmm_nnnnn_ccc_'
  for (j=0;j<4;j++) tmp[j+10]=data[i].a[strlen(data[i].a)-(16-j)];
  //form the 'mmm_nnnnn_ccc_XX.bin'
  for (j=0;j<6;j++) tmp[j+14]=data[i].a[strlen(data[i].a)-(6-j)]; tmp[20]='\0';
/*********************Create names mmm_nnnnn_counter_xx.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 "mmm_counter_nnnnn_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); 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 "mmm_counter_nnnnn_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); 
 fo_work2=fopen(strcat(fno2,"work2.dat"), "wb");
 fo_work2=fopen(fno2, "wb");   //open output help file "work_cln2.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 "mmm_counter_nnnnn_ql.log"
 if(fo_ql==NULL) {cerr<<"can not open ql file"; exit(1);}

/******************************************************************/
/******************************************************************/
 while(feof(fo_log)==0) 
 {
//read PAMELA packet information from Route_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;
  
//  cout<<bitset<8>(error)<<"\n";
//  cout<<bitset<8>(error).test(0)<<"\n";
  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 Route_cln2.pam on packet begin*/
   fo_pam.seekg(adr1-1,ios::beg);
//read PAMELA packet from Route_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);
      
   if(type == 11)  cout<<"time ="<<time<<" moscowtime ="<<moscowtime<<"\n";
   /*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 ((fmod((float)(temp),(float)(10000.))==0.)&&(temp!=0)) cout<<"sorting "<<temp<<"\n";
   /*unpacking several packets....   mikhailov
   unpackingPamelaPacket(packet,type)*/
   
 // if (type == 10) RunHeaderReader(packet);  
   if( type == 11){RunHeaderReader(packet);}
/*******************Packet with type "type"***********************/
   counter[type]+=1;
   //write PAMELA packet in mmm_nnnnn_counter_xx.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 mmm_counter_nnnnn_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 mmm_counter_nnnnn_cln2.pam on error packet begin*/
   fo_pam.seekg(adr1-1,ios::beg);
   //read PAMELA error packet from mmm_counter_nnnnn_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 mmm_nnnnn_conter_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 mmm_counter_nnnnn_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]);

 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;
}
