/*
FILE:     snb.C
*/
/*
VERSION:  1.600
*/
/*
DATE:     2/3/2005
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2005 Rutgers - The State University of New Jersey

This software is provided WITHOUT WARRANTY OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR
IMPLIED.  RUTGERS MAKE NO REPRESENTATION OR WARRANTY THAT THE
SOFTWARE WILL NOT INFRINGE ANY PATENT, COPYRIGHT OR OTHER
PROPRIETARY RIGHT.

The user of this software shall indemnify, hold harmless and defend
Rutgers, its governors, trustees, officers, employees, students,
agents and the authors against any and all claims, suits,
losses, liabilities, damages, costs, fees, and expenses including
reasonable attorneys' fees resulting from or arising out of the
use of this software.  This indemnification shall include, but is
not limited to, any and all claims alleging products liability.
*/
/*
               PDB SOFTWARE LICENSE AGREEMENT

BY CLICKING THE ACCEPTANCE BUTTON OR INSTALLING OR USING 
THIS "SOFTWARE, THE INDIVIDUAL OR ENTITY LICENSING THE  
SOFTWARE ("LICENSEE") IS CONSENTING TO BE BOUND BY AND IS 
BECOMING A PARTY TO THIS AGREEMENT.  IF LICENSEE DOES NOT 
AGREE TO ALL OF THE TERMS OF THIS AGREEMENT
THE LICENSEE MUST NOT INSTALL OR USE THE SOFTWARE.

1. LICENSE AGREEMENT

This is a license between you ("Licensee") and the Protein Data Bank (PDB) 
at Rutgers, The State University of New Jersey (hereafter referred to 
as "RUTGERS").   The software is owned by RUTGERS and protected by 
copyright laws, and some elements are protected by laws governing 
trademarks, trade dress and trade secrets, and may be protected by 
patent laws. 

2. LICENSE GRANT

RUTGERS grants you, and you hereby accept, non-exclusive, royalty-free 
perpetual license to install, use, modify, prepare derivative works, 
incorporate into other computer software, and distribute in binary 
and source code format, or any derivative work thereof, together with 
any associated media, printed materials, and on-line or electronic 
documentation (if any) provided by RUTGERS (collectively, the "SOFTWARE"), 
subject to the following terms and conditions: (i) any distribution 
of the SOFTWARE shall bind the receiver to the terms and conditions 
of this Agreement; (ii) any distribution of the SOFTWARE in modified 
form shall clearly state that the SOFTWARE has been modified from 
the version originally obtained from RUTGERS.  

2. COPYRIGHT; RETENTION OF RIGHTS.  

The above license grant is conditioned on the following: (i) you must 
reproduce all copyright notices and other proprietary notices on any 
copies of the SOFTWARE and you must not remove such notices; (ii) in 
the event you compile the SOFTWARE, you will include the copyright 
notice with the binary in such a manner as to allow it to be easily 
viewable; (iii) if you incorporate the SOFTWARE into other code, you 
must provide notice that the code contains the SOFTWARE and include 
a copy of the copyright notices and other proprietary notices.  All 
copies of the SOFTWARE shall be subject to the terms of this Agreement.  

3. NO MAINTENANCE OR SUPPORT; TREATMENT OF ENHANCEMENTS 

RUTGERS is under no obligation whatsoever to: (i) provide maintenance 
or support for the SOFTWARE; or (ii) to notify you of bug fixes, patches, 
or upgrades to the features, functionality or performance of the 
SOFTWARE ("Enhancements") (if any), whether developed by RUTGERS 
or third parties.  If, in its sole discretion, RUTGERS makes an 
Enhancement available to you and RUTGERS does not separately enter 
into a written license agreement with you relating to such bug fix, 
patch or upgrade, then it shall be deemed incorporated into the SOFTWARE 
and subject to this Agreement. You are under no obligation whatsoever 
to provide any Enhancements to RUTGERS or the public that you may 
develop over time; however, if you choose to provide your Enhancements 
to RUTGERS, or if you choose to otherwise publish or distribute your 
Enhancements, in source code form without contemporaneously requiring 
end users or RUTGERS to enter into a separate written license agreement 
for such Enhancements, then you hereby grant RUTGERS a non-exclusive,
royalty-free perpetual license to install, use, modify, prepare
derivative works, incorporate into the SOFTWARE or other computer
software, distribute, and sublicense your Enhancements or derivative
works thereof, in binary and source code form.

4. FEES.  There is no license fee for the SOFTWARE.  If Licensee
wishes to receive the SOFTWARE on media, there may be a small charge
for the media and for shipping and handling.  Licensee is
responsible for any and all taxes.

5. TERMINATION.  Without prejudice to any other rights, Licensor
may terminate this Agreement if Licensee breaches any of its terms
and conditions.  Upon termination, Licensee shall destroy all
copies of the SOFTWARE.

6. PROPRIETARY RIGHTS.  Title, ownership rights, and intellectual
property rights in the Product shall remain with RUTGERS.  Licensee 
acknowledges such ownership and intellectual property rights and will 
not take any action to jeopardize, limit or interfere in any manner 
with RUTGERS' ownership of or rights with respect to the SOFTWARE.  
The SOFTWARE is protected by copyright and other intellectual 
property laws and by international treaties.  Title and related 
rights in the content accessed through the SOFTWARE is the property 
of the applicable content owner and is protected by applicable law.  
The license granted under this Agreement gives Licensee no rights to such
content.

7. DISCLAIMER OF WARRANTY.  THE SOFTWARE IS PROVIDED FREE OF 
CHARGE, AND, THEREFORE, ON AN "AS IS" BASIS, WITHOUT WARRANTY OF 
ANY KIND, INCLUDING WITHOUT LIMITATION THE WARRANTIES THAT IT 
IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE 
OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE SOFTWARE IS BORNE BY LICENSEE.  SHOULD THE 
SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, THE LICENSEE AND NOT 
LICENSOR ASSUMES THE ENTIRE COST OF ANY SERVICE AND REPAIR.  
THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF 
THIS AGREEMENT.  NO USE OF THE PRODUCT IS AUTHORIZED HEREUNDER 
EXCEPT UNDER THIS DISCLAIMER.

8. LIMITATION OF LIABILITY.  TO THE MAXIMUM EXTENT PERMITTED BY
APPLICABLE LAW,  IN NO EVENT WILL LICENSOR BE LIABLE FOR ANY 
INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 
OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, 
WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 
OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF. 
*/
/*  a program to extract information form the SnB */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "harv.h"
#include "util.h"
#include "nrutil.h"

# define  NW 40
# define NBIN 200
void BNP_statistics(FILE *fout, char *inpfile, char *format, char *method);
void BNP_statistic_shell(FILE *fout,char *inpfile, char *format,char *method);
void BNP_fprime_from_log(FILE *fout,char *inpfile, char *format,char *method);
void BNP_statis_overall(FILE *fout, int nrow, char **text,char *method);
void BNP_statis_set(FILE *fout, int nrow, char **text,char *method);
void BNP_statis_shell(FILE *fout, int nrow, char **text, char *method);


/*************************/
void SNB_phase(FILE *fout, char *inpfile, char *format, char *method)
/* only the heavy atom coordinates  are extracted, since there is no
   phase information available
*/
{
    
    if(!strcmp_case(format, "PDB") ){
        fprintf(fout,"\n\n####### %s heavy atom coordinates ######\n", method);
        heavy_coord_pdb(fout, inpfile, method);
    }else if(!strcmp_case(format, "CIF")){
        write_cif(fout,  inpfile, method);
    }else if(!strcmp_case(format, "LOG")){
        printf("Warning! LOG file from SnB is not supported\n");
        return;
    }else{
        printf("The input format (%s) is wrong!\n", format);
        printf("Please give the correct format (-iCIF,-iPDB).\n");
        usage();
    }
    
}

void BNP_phase(FILE *fout, char *inpfile, char *format, char *method)
{

    
    if(!strcmp_case(format, "PDB") ){
        fprintf(fout,"\n\n####### %s heavy atom coordinates ######\n", method);
        heavy_coord_pdb(fout, inpfile, method);
    }else if(!strcmp_case(format, "CIF")){
        write_cif(fout,  inpfile, method);
    }else if(!strcmp_case(format, "LOG")){
        BNP_statistics(fout,inpfile, format,method);
    }else{
        printf("The input format (%s) is wrong!\n", format);
        printf("Please give the correct format (-iCIF,-iPDB).\n");
        usage();
    }
         
}

void BNP_statistics(FILE *fout, char *inpfile, char *format, char *method)
{
    int   nline=0, n;
    char **text=NULL, str[512];
    
    FILE *fp;

    if((fp = fopen(inpfile, "r")) ==NULL){
        printf("Sorry, can not open the file (%s)\n",inpfile);
        return;
    }

    nline = num_of_line(inpfile);
    

    text = new char *[nline];
    while(fgets(str, sizeof str, fp) != NULL){
        if(pattern5(str,"---","POST REFINEMENT SUMMARY AFTER PASS", "---", "", "")){
            n=0;
            while(fgets(str, sizeof str, fp) != NULL){
                if(pattern5(str, " OCCUPANCY ", ".",".",".",".")||
                   pattern5(str, " BETA  ", ".",".",".",".")) break;
                
                text[n]= new char[strlen(str)+1];
                strcpy(text[n], str);
                n++;
                nline=n;
            }
        }
    }
    
    
    if(nline<5){
        printf("Error! The input file may be wrong or not checked.\n");
        printf("Please send the input file (%s) for us to check.\n", inpfile);
        return;
    }
    
    if(!strcmp_case(method, "MAD"))
        BNP_fprime_from_log(fout, inpfile, format, method);
    BNP_statis_overall(fout, nline, text, method);
    BNP_statis_set(fout, nline, text, method);
    BNP_statis_shell(fout, nline, text, method);
    
    free_memory_2d(text,nline);
    
}
    

void BNP_statis_overall(FILE *fout, int nrow, char **text,char *method)
 //fom, fom_shell
{
    float  a1, a2, reso[NBIN], fom[NBIN], fom_all=0;
    int nref[NBIN], nref_all=0, i, j, n, m, nbin=0, k;
    char meth[40];
    
    for(i=0; i<nrow; i++){ // overall property
                    
        if(strstr_case(text[i],"**** RESULTS FROM COMBINED PROBABILITY DISTRIBUTIONS ***")){
            
            if(pattern5(text[i],"******", "STARTING PHASE REFINEMENT PASS ", "*****", "","")||
               strstr_case(text[i],"DIFFERENCE FOURIER FILE FOR SET"))
                break;

            for(k=i; k<nrow; k++){
                if(pattern5(text[k],"MEAN FIGURE OF MERIT =",".","FOR", "PHASED REFLECTIONS","")){
                    fom_all = get_float(text[k],"=", "FOR");
                    nref_all = get_int(text[k], "FOR","PHASED");
                }else if(strstr_case(text[k],"< FOM >        < d >     No. Refl")){
                    
                    m =0;
                    for(j=k; j<nrow; j++){
                        if(strstr_case(text[j]," PHASING POWER BREAKDOWN BASED ON CURRENT PROTEIN PHASES")||
                           strstr_case(text[j], "set")) break;
                    
                        if(sscanf(text[j], "%f%f%d", &a1,  &a2,  &n) == 3){
                            fom[m] = a1;
                            reso[m] = a2;
                            nref[m] = n;
                            m++;
                            nbin =m;
                        }
                    }
                    k=j-1;
                }
                
            }
            i=k-1; 
        }
    }
    
    if(nbin>1){
        if(!strcmp_case(method,"MAD")){
            
            fprintf(fout,"\n\n");
            if(reso[nbin-1]>0)fprintf(fout,"_phasing_MAD.entry_id  '%s'\n",DATA_BLOCK);
            fprintf(fout,"_phasing_MAD.pdbx_d_res_high  %.2f\n",reso[0]);
            fprintf(fout,"_phasing_MAD.pdbx_d_res_low  .\n");
            if(nref_all>0)fprintf(fout,"_phasing_MAD.pdbx_Reflns  %d\n",nref_all);
            if(fom_all>0)fprintf(fout,"_phasing_MAD.pdbx_fom  %.3f\n",fom_all);
            
            fprintf(fout,"\n\n");

            strcpy(meth,"_pdbx_phasing_MAD_shell");     
            fprintf(fout,"\nloop_\n");
            fprintf(fout,"%s.d_res_high \n",meth);
            fprintf(fout,"%s.d_res_low  \n",meth);
            fprintf(fout,"%s.Reflns    \n",meth);
            fprintf(fout,"%s.fom  \n",meth);
            
            for(i=0; i<nbin-1; i++){
                fprintf(fout,"%.2f %.2f   %d %.3f\n", reso[i],reso[i+1], nref[i], fom[i]);
            }
            fprintf(fout,"%.2f .  %d %.3f\n", reso[nbin-1], nref[nbin-1], fom[nbin-1]);
            
        }else if(!strcmp_case(method,"MIR")){
            
            fprintf(fout,"\n\n");
            fprintf(fout,"_phasing_MIR.entry_id  '%s'\n",DATA_BLOCK);
            if(reso[nbin-1]>0) fprintf(fout,"_phasing_MIR.pdbx_d_res_high  %.3f\n",reso[0]);
            fprintf(fout,"_phasing_MIR.pdbx_d_res_low  .\n");
            if(nref_all>0)fprintf(fout,"_phasing_MIR.pdbx_Reflns  %d\n",nref_all);
            if(fom_all>0)fprintf(fout,"_phasing_MIR.pdbx_fom  %.3f\n",fom_all);

            fprintf(fout,"\n\n");

            strcpy(meth,"_phasing_MIR_shell");     
            fprintf(fout,"\nloop_\n");
            fprintf(fout,"%s.d_res_high \n",meth);
            fprintf(fout,"%s.d_res_low  \n",meth);
            fprintf(fout,"%s.Reflns    \n",meth);
            fprintf(fout,"%s.fom  \n",meth);
            
            for(i=0; i<nbin-1; i++){
                fprintf(fout,"%.2f %.2f   %d %.3f\n", reso[i],reso[i+1], nref[i], fom[i]);
            }
            fprintf(fout,"%.2f .  %d %.3f\n", reso[nbin-1], nref[nbin-1], fom[nbin-1]);
            
            
        }
    }
}


void BNP_statis_set(FILE *fout, int nrow, char **text,char *method)
{
    char tmp1[512], tmp2[512], setid[NW][80], meth[90];
    int  i, j=0, k=0, n,m, deriv1[NW], n1=0, n2=0, n3=0,n4=0,nbin=0, num, mm;
    float rc_c[NW],rk_a[NW], fom_c[NW], fom_a[NW], fom[NW], pp[NW];
    float   a1, a2,reso[NW][NBIN];
    
    for(n=0; n<=NW; n++) {
        rc_c[n] = -9999;
        rk_a[n] = -9999;
        fom_a[n] = -9999;
        fom_c[n] = -9999;
        fom[n] = -9999;
        strcpy(setid[n], "?");
        
    }
    
    
    
    n=0;
    for(i=0; i<nrow; i++){ /*POST REFINEMENT SUMMARY (rc_c, rk_a)*/
        if(strstr_case(text[i],"START OF NEXT PHASIN")||
           strstr_case(text[i],"INDIVIDUAL DATA SET RES")) break;
        if(pattern5(text[i], "STATISTICS FOR SET", "AFTER REFINEMENT", "","","")){
            if(n>=NW){
                printf("Warning! Too many data sets!\n");
                return;
            }
            n++;
            deriv1[n]=get_int(text[i],"SET","AFTER");
        }else  if(pattern5(text[i],"R CULLIS =", "FOR", " CENTRIC REFLECTIONS","","")){
            rc_c[n] = get_float(text[i],"=","FOR");
            
        }else if(pattern5(text[i],"R KRAUT  =", "FOR", " ACENTRIC REFLECTIONS","","")){
            rk_a[n] = get_float(text[i],"=","FOR");
            
        }    
    }
    n1=n;
    k=i-1;
    
    
    n=0;
    for(i=k; i<nrow; i++){ // fom for each set
        if(strstr_case(text[i],"** RESULTS FROM COMBINED PROBABILITY DISTRIBUTIONS **")) break;

        if(sscanf(text[i],"%s%d%s", tmp1, &num, tmp2)==3 &&
           (pattern5(text[i],"SET ", "_iso", "", "", "") ||
           pattern5(text[i],"SET ", "_ano", "", "", ""))){
            if(n>=NW){
                printf("Warning! Too many data sets!\n");
                return;
            }
                
            n++;
            deriv1[n] = num;
            strcpy(setid[n], tmp2);
            
        }else if(pattern5(text[i],"MEAN FIGURE OF MERIT =", "FOR", "REFLECTIONS","","")&&
                 !strstr_case(text[i],"CENTRIC")){
            fom[n] = get_float(text[i],"=","FOR");
            
        }else if(pattern5(text[i],"MEAN FIGURE OF MERIT =", "FOR", " CENTRIC REFLECTIONS","","")){
            fom_c[n] = get_float(text[i],"=","FOR");
            
        }else if(pattern5(text[i],"MEAN FIGURE OF MERIT =", "FOR", " ACENTRIC REFLECTIONS","","")){
            fom_a[n] = get_float(text[i],"=","FOR");
            
        }
    }
    
    n2=n;
    k=i-3;

    
    n=0;
    for(i=k; i<nrow; i++){ // fom for each set

        if(sscanf(text[i],"%s%d%s", tmp1, &num, tmp2)==3 &&
           (pattern5(text[i],"SET ", "_iso", "", "", "") ||
           pattern5(text[i],"SET ", "_ano", "", "", ""))){
            
            if(n>=NW){
                printf("Warning! Too many data sets!\n");
                return;
            }
                
            n++;
            deriv1[n] = num;
            strcpy(setid[n], tmp2);
            
        }else if(pattern5(text[i],"OVERALL MEAN d =", ".", "PHASING POWER =",".","")){
            
            pp[n] = get_float(text[i],"POWER =","\n");
            
        }
    }
    n3=n;

    n=0;
    
    for(i=0; i<nrow; i++){ // resolution
        if(strstr_case(text[i]," < d >     Phasing Power    Bias   No. Refl")){
            if(n>=NW){
                printf("Warning! Too many data sets!\n");
                return;
            }   
            n++;
            m=0;
            for (j=i; j<nrow; j++){
                if(pattern5(text[j], "OVERALL MEAN d =", ".", "PHASING POWER =", ".", "")) break;
                mm = sscanf( text[j], "%f %f %f %d", &a1, &a2, &a2,&num);
                
                if(mm ==4){
                    m++;
                    nbin=m;
                    if(m>=NBIN){
                        printf("Warning! Too many bins!\n");
                        return;
                    }
                    reso[n][m] = a1;
                }
            }
        }
    }
    n4=n;
        /*
    for(i=1; i<=n; i++)
        printf("n1=%d %d %d %d %d %d %.3f  %.3f %.3f %.3f %.3f %.3f\n", nbin
               ,n1, n2,n3,n4,deriv1[i], rc_c[i], rk_a[i], fom[i],fom_a[i],fom_c[i], pp[i]);
        */
    
    if(!(n1>0 && n1==n2 && n1==n3 && n1==n4 && nbin>0 )) return;
    

    fprintf(fout,"\nloop_\n");
    if(!strcmp_case(method,"MAD")){
        strcpy(meth,"_pdbx_phasing_MAD_set");
        
        fprintf(fout,"%s.id \n",meth);
        fprintf(fout,"%s.d_res_low \n",meth);
        fprintf(fout,"%s.d_res_high \n",meth);
        fprintf(fout,"%s.fom_centric \n",meth);
        fprintf(fout,"%s.fom_acentric \n",meth);
        fprintf(fout,"%s.fom \n",meth);
        fprintf(fout,"%s.R_cullis_centric \n",meth);
        fprintf(fout,"%s.R_kraut_acentric \n",meth);
        fprintf(fout,"%s.power \n",meth);
        
        for(i=1; i<=n1; i++){
            fprintf(fout, " '%s'", setid[i]);
            (reso[i][1]>0) ? fprintf(fout, " %.2f ", reso[i][1]) : fprintf(fout, " ? ");
            (reso[i][nbin]>0) ? fprintf(fout, " %.2f ", reso[i][nbin]) : fprintf(fout, " ? ");
            (fom_c[i]>0) ? fprintf(fout, " %.3f ", fom_c[i]) : fprintf(fout, " ? ");
            (fom_a[i]>0) ? fprintf(fout, " %.3f ", fom_a[i]) : fprintf(fout, " ? ");
            (fom[i]>0) ? fprintf(fout, " %.3f ", fom[i]) : fprintf(fout, " ? ");
            (rc_c[i]>0) ? fprintf(fout, " %.3f ", rc_c[i]) : fprintf(fout, " ? ");
            (rk_a[i]>0) ? fprintf(fout, " %.3f ",rk_a[i] ) : fprintf(fout, " ? ");
            (pp[i]>0) ? fprintf(fout, " %.3f ",pp[i] ) : fprintf(fout, " ? ");
        }
        
    }else if(!strcmp_case(method,"MIR")){
        strcpy(meth,"_phasing_MIR_der");
            
        fprintf(fout,"%s.id \n",meth);
        fprintf(fout,"%s.der_set_id \n",meth);
        fprintf(fout,"%s.native_set_id \n",meth);
        fprintf(fout,"%s.d_res_low \n",meth);
        fprintf(fout,"%s.d_res_high \n",meth);
        fprintf(fout,"%s.pdbx_fom_centric \n",meth);
        fprintf(fout,"%s.pdbx_fom_acentric \n",meth);
        fprintf(fout,"%s.pdbx_fom \n",meth);
        fprintf(fout,"%s.R_cullis_centric \n",meth);
        fprintf(fout,"%s.pdbx_R_kraut_acentric \n",meth);
        fprintf(fout,"%s.pdbx_power \n",meth);

        for(i=1; i<=n1; i++){
            fprintf(fout, " '%s' %d  1", setid[i], deriv1[i]);
            (reso[i][1]>0) ? fprintf(fout, " %.2f ", reso[i][1]) : fprintf(fout, " ? ");
            (reso[i][nbin]>0) ? fprintf(fout, " %.2f ", reso[i][nbin]) : fprintf(fout, " ? ");
            (fom_c[i]>0) ? fprintf(fout, " %.3f ", fom_c[i]) : fprintf(fout, " ? ");
            (fom_a[i]>0) ? fprintf(fout, " %.3f ", fom_a[i]) : fprintf(fout, " ? ");
            (fom[i]>0) ? fprintf(fout, " %.3f ", fom[i]) : fprintf(fout, " ? ");
            (rc_c[i]>0) ? fprintf(fout, " %.3f ", rc_c[i]) : fprintf(fout, " ? ");
            (rk_a[i]>0) ? fprintf(fout, " %.3f ",rk_a[i] ) : fprintf(fout, " ? ");
            (pp[i]>0) ? fprintf(fout, " %.3f ",pp[i] ) : fprintf(fout, " ? ");
        }
    }
    
}


void BNP_statis_shell(FILE *fout, int nrow, char **text, char *method)
{
    char  tmp[512], tmp1[512], tmp2[512], meth[60], setid[NW][80];
    int i, j, k, n=0, m, num, nr, nref[NW][NBIN], nset[NW];
    float pp[NW][NBIN], resol[NW][NBIN], value1, value;

    for(k=0; k<nrow; k++){ /* (phase power shell) */
        if(strstr_space(text[k], "PHASING POWER BREAKDOWN BASED ON "))break;
    }
    
    for(i=k; i<nrow; i++){
        upperstr(text[i]);
        if(strstr_space(text[i],"DIFFERENCE FOURIER FILE"))break;
        
        if(pattern5(text[i]," SET ","_ISO", "","", "") ||
           pattern5(text[i]," SET ","_ANO", "","", "")){
            strcpy(tmp, strstr(text[i],"SET"));
            n=sscanf(tmp, "%s%d%s",tmp1,&num,tmp2);
            if(n==3) strcpy(setid[num], tmp2);
            
        }
        if(pattern5(text[i],"d ","Phasing", "Bias","Refl", "")){
            n=1;
            for(j=i+1; j<nrow; j++){
                m=sscanf(text[j], "%f%f%*s%d",&value,&value1,&nr);
                if(m==3){
                    resol[num][n] = value;
                    pp[num][n] = value1;
                    nref[num][n] = nr;
                    n++;
                    
                }
                if(strstr_space(text[j], "OVERALL MEAN")){
                    nset[num]=n;
                    i=j-1;
                    break;
                }
            }
        }
    }
    fprintf(fout,"\n\n#++++++ %s BnP phasing summary+++++++++++++\n", method);

//    printf("\n METHOD %s\n", method);
    if(num<1)return;
    
    fprintf(fout,"\nloop_\n");
    if(!strcmp_case(method,"MAD")){
        strcpy(meth,"_pdbx_phasing_MAD_set_shell");
        
        fprintf(fout,"%s.id \n",meth);
        fprintf(fout,"%s.d_res_low \n",meth);
        fprintf(fout,"%s.d_res_high \n",meth);
        fprintf(fout,"%s.power \n",meth);
        fprintf(fout,"%s.reflns\n",meth);
        
    } else if(!strcmp_case(method,"MIR")){
        strcpy(meth,"_phasing_MIR_der_shell");

        fprintf(fout,"%s.der_id \n",meth);
        fprintf(fout,"%s.d_res_low \n",meth);
        fprintf(fout,"%s.d_res_high \n",meth);
        fprintf(fout,"%s.power \n",meth);
        fprintf(fout,"%s.reflns \n",meth);
    }

                    
    for(i=1; i<=num; i++){
        for(j=1; j<nset[i]; j++){
            if(j==1)
                fprintf(fout, "'%s' ?  %.3f  %.3f  %d\n",
                        setid[i], resol[i][j], pp[i][j], nref[i][j]);
            else
                fprintf(fout, "'%s'  %.3f  %.3f   %.3f  %d\n",
                        setid[i], resol[i][j-1],resol[i][j], pp[i][j], nref[i][j]);
                
        }
    }
    
}



void BNP_fprime_from_log(FILE *fout, char *inpfile, char *format, char *method)
        /* get fprime and fdouble prime from log file*/
{

    char str[512], tmp[512];
    int n, i;
    float fprime[NW],fdprime[NW], value;
    FILE *fp;

    if((fp = fopen(inpfile, "r")) ==NULL){
        printf("Sorry, can not open the file (%s)\n",inpfile);
        return;
    }
       
    
    n=1;
    while(fgets(str, sizeof str, fp) != NULL){
        if(pattern5(str,"FOR ATOM TYPE ", "DELTA f PRIME =", ".", "DELTA f DOUBLE PRIME =", ".")){
            strcpy(tmp, strchr(str, '=')+1);
            if(sscanf(tmp, "%f", &value) == 1){
                fprime[n]=value;
                strcpy(tmp, strrchr(str, '=')+1);
                if(sscanf(tmp, "%f", &value) == 1){
                    fdprime[n]=value;
                    n++;
                }
            }
        }
        if(n>=NW){
            printf("Error! check the input file (%s) or check format (%s)\n",
                   inpfile, format);
            return;
        }
        if(pattern5(str, "set", "_iso", "", "", "") ||
           pattern5(str, "set", "_ano", "", "", "")) break;
    }
    if(n<=1) return;
    
    if(!strcmp_case(method,"MIR") || !strcmp_case(method,"SIR"))return;
    
    fprintf(fout,"\n\n#++++++ MAD wavelength+++++++++++++\n" );    
    fprintf(fout,"loop_\n");
    fprintf(fout,"_phasing_%s_set.expt_id\n",method);
    fprintf(fout,"_phasing_%s_set.clust_id\n",method);
    fprintf(fout,"_phasing_%s_set.set_id\n",method);
    fprintf(fout,"_phasing_%s_set.f_prime\n",method);
    fprintf(fout,"_phasing_%s_set.f_double_prime\n",method);
    
    for(i=1; i<n; i++){
        fprintf(fout, "1 '%d wavelength' %d   %.2f   %.2f\n",
                n,i, fprime[i],  fdprime[i]);
    }

    fclose(fp);
    
}


