/*
FILE:     ccp4.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 CCP4 program */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "structure.h"
#include "harv.h"
#include "nrutil.h"
#include "util.h"

#define LEN 256
#define NBIN 100

void mlphare_log(FILE *fout, char *inpfile, char *method);

//PHASING_MIR  phasing_mir ;
extern  CELL cell ;
extern SYMMETRY symmetry;
extern PDBX_PHASING_DM  pdbx_phasing_dm;
PDBX_PHASING_DM_SHELL  pdbx_phasing_dm_shell;
extern PDBX_PHASING_MR pdbx_phasing_MR;

extern REFINE refine;


PHASING_MAD phasing_mad;
PDBX_PHASING_MAD_SET pdbx_phasing_mad_set;
PDBX_PHASING_MAD_SET_SHELL pdbx_phasing_mad_set_shell[NBIN];
PDBX_PHASING_MAD_SET_SITE pdbx_phasing_mad_set_site;
PDBX_PHASING_MAD_SHELL pdbx_phasing_mad_shell[NBIN];
PHASING_MAD_SET phasing_mad_set;


PHASING_MIR phasing_mir;
PHASING_MIR_DER phasing_mir_der;
PHASING_MIR_DER_SHELL phasing_mir_der_shell;
PHASING_MIR_DER_SITE phasing_mir_der_site;
PHASING_MIR_SHELL phasing_mir_shell;

void convert_restr_refmac5_cif(char *str);

void CCP4_phase_file_assign(FILE *fout, char *inpfile, char *format,
                            char *method)
/* assign the files (from phasing) to different subroutines */
{
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s (routine:CCP4_phase_file_assign)\n",
               inpfile);
        return;
    }

    if(!strcmp_case(format, "PDB")) { /*take as heavy atom XYZ */
        heavy_coord_pdb(fout, inpfile, method);
        return;
    }
/* must be prephadata log file and mlphare log file*/
    if(!strcmp_case(format, "LOG")) { 
        CCP4_MAD_wave(fout, inpfile, method);
        mlphare_log(fout, inpfile,method);
        
        return;
    }
    
    if(!strcmp_case(format, "CIF")) {
        
        CCP4_mlphare_cif(fout, inpfile, method);
        return;
    }
    fclose(fp);
    
}

       
    
void mlphare_log(FILE *fout, char *inpfile, char *method)
{
    char  tmp[80], **str=NULL, **line=NULL, **atom=NULL, **deriv=NULL, bfact[30];
    int  n,m,i,k, j,nline, ntoken=0, nbin=0, na, nd, nr;
    
    int refl_sh[NBIN],refl_a_sh[NBIN], refl_c_sh[NBIN], refl=0,refl_a=0, refl_c=0;
    float fom_sh[NBIN],fom_a_sh[NBIN], fom_c_sh[NBIN],resL_sh[NBIN],resH_sh[NBIN];
    
    int ref_a_sh[500][NBIN], ref_c_sh[500][NBIN], ref_a[500], ref_c[500];
    float loc_a_sh[500][NBIN], php_a_sh[500][NBIN], rc_a_sh[500][NBIN];
    float loc_c_sh[500][NBIN], php_c_sh[500][NBIN], rc_c_sh[500][NBIN];
    float loc_a[500], php_a[500], rc_a[500], loc_c[500], php_c[500], rc_c[500];
    
    float fom=0, fom_a=0, fom_c=0, *resL_set,*resH_set ;
    int n1, n2,n3, n4,n5,n6;
    
    float a1, a2, a3, a4, a5, a6;
    FILE *fp;
 
// 500 max derivatives
    
    const char *phasing_shell[8] = 
        {
            "d_res_high",
            "d_res_low",
            "reflns",
            "fom",
            "reflns_centric",
            "FOM_centric",
            "reflns_acentric",
            "FOM_acentric"
        };
        
    const char *items_site[7] = 
        {
            "id",
            "atom_type_symbol",
            "fract_x",
            "fract_y",
            "fract_z",
            "B_iso",
            "Occupancy"
        };
        
    const char *item_der_shell[12] = 
        {
            "der_id",
            "id",
            "d_res_high",
            "d_res_low",
            "pdbx_reflns_acentric",
            "pdbx_loc_acentric",
            "pdbx_power_acentric",
            "pdbx_R_cullis_acentric",
            "pdbx_reflns_centric",
            "pdbx_loc_centric",
            "pdbx_power_centric",
            "pdbx_R_cullis_centric",
        };
    
   
   
    if((fp=fopen(inpfile, "r"))==NULL)
       open_file_error(inpfile, "mlphare_log");
    
    str  = get_lines_from_file(inpfile, &nline);
    
//    for(n=0; n<nline; n++)printf("%s\n",str[n]);
    phasing_mir_shell.nbin = 0;
    
    for(i=0; i<nline-1; i++){
        
        if (strstr_space(str[i], "* Cell Dimensions :") && i<nline-1){
            n=sscanf(str[i+1],"%f%f%f%f%f%f", &a1, &a2, &a3, &a4, &a5, &a6);
            if( n==6 ){
                cell.length_a = a1;
                cell.length_b = a2;
                cell.length_c = a3;
                cell.angle_alpha = a4;
                cell.angle_beta = a5;
                cell.angle_gamma = a6;        
            }
        }else if(pattern5(str[i], "Space group =", "(number", ")", "", "") ){
            strcpy(tmp, "");
            strcpy(tmp, get_substr(str[i],"Space group =", "(number"));
            char2space(tmp, '\'');
            if(strlen(tmp)>0) strcpy(symmetry.space_group_name_H_M, tmp);
            strcpy(tmp, "");
            strcpy(tmp, get_substr(str[i],"number", ")"));
            if(strlen(tmp)>0) symmetry.Int_Tables_number= atoi(tmp);
            
        }else if(strstr_space(str[i], "Protein Resolution Limits are from") &&
                 pattern5(str[i], "from" , "to", "Angstroms", "", "")){
            phasing_mad.pdbx_d_res_low  = get_float(str[i],"from","to");
            phasing_mad.pdbx_d_res_high = get_float(str[i],"to", "Angstroms");
            
        }else if(strstr_space(str[i], "Resolution of each shell in angstroms:")){
            line = string_token(str[i+1]," " , &ntoken);
            nbin = ntoken;
            resL_sh[0] = phasing_mad.pdbx_d_res_low;
            resH_sh[0] = atof(line[0]);
            for(k=1; k<ntoken; k++){
                resL_sh[k] = atof(line[k-1]);
                resH_sh[k] = atof(line[k]);
            }
            
            
            phasing_mir_shell.nbin = ntoken;
            phasing_mir_shell.d_res_low[0] = phasing_mad.pdbx_d_res_low;
            phasing_mir_shell.d_res_high[0] = atof(line[0]);
            
            for(k=1; k<ntoken; k++){
                phasing_mir_shell.d_res_low[k] = atof(line[k-1]);
                phasing_mir_shell.d_res_high[k] = atof(line[k]);
            }
           
            
        }else if(i<nline-10 &&
                 strstr_space(str[i],"Number of Measurements phased -ACENTRIC  TOTAL")&&
                 strstr_space(str[i+2],"Mean Figure of Merit")&&
                 strstr_space(str[i+4],"Number of Measurements phased -CENTRIC  TOTAL")&&
                 strstr_space(str[i+6],"Mean Figure of Merit")&&
                 strstr_space(str[i+8],"Number of Measurements phased -ALL  TOTAL")&&
                 strstr_space(str[i+10],"Mean Figure of Merit")
                 ){
            
            line = string_token(str[i+1]," " , &n1);
            if(nbin == n1-1){
                for(k=0; k<n1-1; k++){
                    refl_a_sh[k] = atoi(line[k]);
                }
                refl_a = atoi(line[n1-1]);
            }
            
            line = string_token(str[i+3]," " , &n2);
            if(nbin == n2 -1){
                for(k=0; k<n2 -1; k++){
                    fom_a_sh[k] = atof(line[k]);
                }
                fom_a = atof(line[n2 -1]);
            }

            line = string_token(str[i+5]," " , &n3 );
            if(nbin == n3 -1){
                for(k=0; k<n3 -1; k++){
                    refl_c_sh[k] = atoi(line[k]);
                }
                refl_c = atoi(line[n3 -1]);
            }

            line = string_token(str[i+7]," " , &n4 );
            if(nbin == n4 -1){
                for(k=0; k<n4 -1; k++){
                    fom_c_sh[k] = atof(line[k]);
                }
                fom_c = atof(line[n4 -1]);
            }

            line = string_token(str[i+9]," " , &n5 );
            if(nbin == n5 -1){
                for(k=0; k<n5 -1; k++){
                    refl_sh[k] = atoi(line[k]);
                }
                refl = atoi(line[n5 -1]);
            }
            
            line = string_token(str[i+11]," " , &n6 );
            if(nbin == n6 -1){
                for(k=0; k<n6 -1; k++){
                    fom_sh[k] = atof(line[k]);
                }
                fom = atof(line[n6 -1]);
            }

            i=i+10;
            
        }
        
            
    }

  
    if(nbin ==n1-1 && n1==n2&& n1==n3&& n1==n4&& n1==n5&& n1==n6){
        if(!strcmp_case(method,"mir"))
           print_mmcif_head(fout, "_phasing_MIR_shell", phasing_shell, 8);
        else
           print_mmcif_head(fout, "_pdbx_phasing_MAD_shell", phasing_shell, 8);
            
        for(i=0; i<nbin; i++){
            fprintf(fout, "%.2f %.2f  %d %.3f  %d %.3f  %d %.3f\n",
                    resH_sh[i], resL_sh[i],refl_sh[i],fom_sh[i],
                    refl_c_sh[i],fom_c_sh[i],refl_a_sh[i],fom_a_sh[i]);
        }
        
        if(!strcmp_case(method,"mir"))
            print_mmcif_head(fout, "_phasing_MIR", phasing_shell, 8);
        else
            print_mmcif_head(fout, "_phasing_MAD", phasing_shell, 8);
            
        fprintf(fout, "%.2f %.2f  %d %.3f  %d %.3f  %d %.3f\n",
                resH_sh[nbin-1], resL_sh[0],refl,fom,refl_c,fom_c,refl_a,fom_a);
    }
    
    
//atom site coordinates
    na=0;
    nd=0;
    nr=0;
    
    for(i=0; i<nline-1; i++){
        if (strstr_case(str[i],"MLPHARE:  Normal termination"))break;
        if (strstr_case(str[i],"END OF MLPHARE PROCEDURE")){
            for(j=i+1; j<nline-1; j++){
                rid_of_front_space(str[j]);
                if( !strncmp(str[j],  "DERIV ", 6) )nd++;
                if(!strncmp(str[j],  "RESO   ", 7) )nr++;
                
                if(pattern5(str[j],"ATOM", "Bfac ","", "", ""))na++;
            }
        }
    }
        
//    printf("3nr,nd, na %d %d %d\n",nr,nd, na );
    atom =new char *[na+1];
    deriv = new char *[nd+1];
    resL_set = new float [nr+1];
    resH_set = new float [nr+1];
    
    na=0;
    nd=0;
    nr = 0;
   
    for(i=0; i<nline-1; i++){
        if (strstr_case(str[i],"MLPHARE:  Normal termination"))break;
        if (strstr_case(str[i],"END OF MLPHARE PROCEDURE")){
            for(j=i+1; j<nline-1; j++){
                rid_of_front_space(str[j]);
                
                if( !strncmp(str[j],  "DERIV ", 6) ){
                    deriv[nd] = new char [80];
                    strcpy(deriv[nd], get_string_after_id_length(str[j], "DERIV",30));
                    rid_of_front_end_space(deriv[nd]);
                    
                    nd++;
                
                }else if(!strncmp(str[j],  "RESO   ", 7) ){
                    n=sscanf(str[j],"%*s%f%f", &a1, &a2);
                    
                    if(n ==2){
                        resL_set[nr] = a1;
                        resH_set[nr] = a2;
                        nr++;
                       
                    }
                    

                }else if(pattern5(str[j],"ATOM", "Bfac","", "", "")){
                    atom[na] = new char[80];
                   
                    n=sscanf(str[j], "%*s %s %f %f %f %f ",
                             tmp, &a1, &a2, &a3, &a4);
                    strcpy(bfact, get_string_after_id_number(str[j], "bfac",1));
                    if (n==5 && bfact ){
                        sprintf(atom[na], "%s %.3f %.3f %.3f %s  %.3f ",
                                tmp,a1, a2, a3, bfact, a4);
                        na++;
                    }
                }
            }
        }
    }
    
    if(na>0 && nd>0 && nr == nd){
        if(!strcmp_case(method,"mir"))
            print_mmcif_head(fout,"_phasing_MIR_der_site", items_site, 7);
        else
            print_mmcif_head(fout,"_pdbx_phasing_MAD_set_site", items_site, 7);
            
        for(i=0; i<na; i++){
            fprintf(fout, "%d  %s\n",i+1, atom[i]);
        }
    }
// end  atom site coordinates   

    
//  Phasing statistics: phasing Power, Lack_of_closure, R_Cullis(censtric, acentric)
    m=0;
    for(i=0; i<nline-1; i++){
        if(strstr_case(str[i],"1/resol^2  Resol   Nref_a DISO_a LOC_a PhP_a CullR_a Nref_c DISO_c LOC_cPhP_c CullR_c")  ){
            n=0;
            if (strstr_case(str[i],"END OF MLPHARE PROCEDURE")||
                strstr_case(str[i],"MLPHARE:  Normal termination")){
                nbin=n;
                break;
            }
            
            
            for(k=i+1; k<nline-1; k++){
                ref_a_sh[m][n] = get_int_by_length(str[k],17, 24);
                loc_a_sh[m][n]  = get_float_by_length(str[k],32,38);
                php_a_sh[m][n]  = get_float_by_length(str[k],39,43);
                rc_a_sh[m][n]  = get_float_by_length(str[k],44,51);
                ref_c_sh[m][n]  = get_int_by_length(str[k],51,58);
                loc_c_sh[m][n]  = get_float_by_length(str[k],66,72);
                php_c_sh[m][n]  = get_float_by_length(str[k],73, 77);
                rc_c_sh[m][n]  = get_float_by_length(str[k],78, 84);
                n++;
                
                
                if(strstr_case(str[k], "total")){

                    ref_a[m] = get_int_by_length(str[k],17, 24);
                    loc_a[m] = get_float_by_length(str[k],32,38);
                    php_a[m]  = get_float_by_length(str[k],39,43);
                    rc_a[m]  = get_float_by_length(str[k],44,51);
                    ref_c[m]  = get_int_by_length(str[k],51,58);
                    loc_c[m] = get_float_by_length(str[k],66,72);
                    php_c[m]  = get_float_by_length(str[k],73, 77);
                    rc_c[m]  = get_float_by_length(str[k],78, 84);
                    break;
                }
            }   
            m++;       
        }
    }
    
//    printf("3nr,nd, na %d %d %d %d\n",nr,nd, m,nbin);

    if(m>0){
        if(!strcmp_case(method,"mir"))
            print_mmcif_head(fout, "_phasing_MIR_der_shell", item_der_shell, 12);
        else
            print_mmcif_head(fout, "_pdbx_phasing_MAD_set_shell", item_der_shell, 12);      
        for(j=0; j<m; j++){
            for(k=0; k<nbin; k++){  
                fprintf(fout, " '%s' %d %.2f %.2f  %d %.3f %.3f %.3f    %d %.3f %.3f %.3f\n",
                        deriv[j], j+1,resH_sh[k], resL_sh[k], 
                        ref_a_sh[j][k],loc_a_sh[j][k],php_a_sh[j][k],rc_a_sh[j][k],
                        ref_c_sh[j][k],loc_c_sh[j][k],php_c_sh[j][k],rc_c_sh[j][k]);
            }
        }
    }
        
    if(m == nr){
        if(!strcmp_case(method,"mir"))
            print_mmcif_head(fout, "_phasing_MIR_der", item_der_shell, 12);
        else
            print_mmcif_head(fout, "_pdbx_phasing_MAD_set", item_der_shell, 12);
            
        for(j=0; j<m; j++){
            fprintf(fout, "'%s'  %d %.2f %.2f  %d %.3f %.3f %.3f    %d %.3f %.3f %.3f\n",
                    deriv[j],j+1,resH_set[j],resL_set[j],
                    ref_a[j],loc_a[j],php_a[j],rc_a[j],
                    ref_c[j],loc_c[j],php_c[j],rc_c[j]);
        }
          
    }

    delete [] atom;
    delete [] deriv;
    fclose(fp); 
    
}

void CCP4_MAD_wave(FILE *fout, char inpfile[], char method[])
/* extract the wavelength information from *_prephadata.log file */
{
    char str[512];
    int num=0,id[20], n=0 , i;
    float wave[20], fprime[20], f2prime[20];
    FILE *fp;

    if(!strcmp_case(method,"SIR") || !strcmp_case(method,"MIR"))return;

    fprintf(fout,"\n######## the wavelength information ########\n\n");
            
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_MAD_wave)\n",inpfile);
        return;
    }

    while (fgets(str, sizeof str, fp) != NULL) {
       
        if(strstr_space(str, "Ndata Wavelengths      Fprime   Fdoublepr")){
            n=0;
            while (fgets(str, sizeof str, fp) != NULL){
                num=sscanf(str,"%d %f %f %f",
                           &id[n], &wave[n], &fprime[n], &f2prime[n]);
                
                if(strstr_space(str,"Data will be excluded if the") ||
                   strstr_space(str,"file opened on unit" ))
                    break;
                if(num ==4 ){
                    n++;
                }  
            }
            break;
        }
    }

    if(n>0) {     
        fprintf(fout,"\nloop_\n"
                "_phasing_MAD_set.expt_id\n"
                "_phasing_MAD_set.clust_id\n"
                "_phasing_MAD_set.set_id\n"
                "_phasing_MAD_set.wavelength\n"
                "_phasing_MAD_set.f_prime\n"
                "_phasing_MAD_set.f_double_prime\n"
                );
        
        for( i=0; i<n; i++){
            fprintf(fout, "1  '%d wavelength' %d %.3f %.3f %.3f\n",
                    n, id[i], wave[i], fprime[i], f2prime[i] );
        }
    }
    
           
    fprintf(fout, "#\n\n");
    fclose(fp);
}

void CCP4_mlphare_cif(FILE *fout, char inpfile[], char method[])
/* append the *.mlphare to the cif file; do not need data block and entry ID */ 
{

    char tmp[512], str[512], category[512],item[512];
    int ncat=0;
    
    FILE *fp;
    
    fprintf(fout, "\n\n########## Mlphare phasing information #########\n\n");
    

    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_mlphare_cif)\n",inpfile);
        return;
    }
    if( is_cif(inpfile)< 5) {
        printf("The input file (%s) for mlphare is not in mmCIF format",inpfile);
        return;
    }
    
    if(!strcmp_case(method,"MIR")){
        while (fgets(str, sizeof str, fp) != NULL) {
            strcpy(tmp, str);
            upperstr(tmp);
            rid_of_front_space(tmp);
            if(!strncmp_case(tmp, "DATA_",5)||
               !strncmp_case(tmp, "_audit.creation_date",20) || 
               !strncmp_case(tmp, "_ENTRY.ID",9))
                continue;
            fprintf(fout, "%s", str);
        }
        fclose(fp);
        return;
        
    }else if (!strcmp_case(method,"MAD")){
        while (fgets(str, sizeof str, fp) != NULL) {
            strcpy(tmp, str);
            upperstr(tmp);
            rid_of_front_space(tmp);
            if(!strncmp_case(tmp, "DATA_", 5) ||
               !strncmp_case(tmp, "_audit.creation_date",20) ||
               !strncmp_case(tmp, "_ENTRY.ID", 9))
                continue;
            
            ncat = check_category(str, category, item);
//            if (ncat>0)printf("hello item=%s   %s\n", category,item);
            
            strcpy(tmp,str);

            if(!strcmp_case(category,  "_PHASING_MIR_SHELL") && ncat>0){
               replace_first_str(tmp,"_PHASING_MIR","_pdbx_phasing_MAD",str);
                         
            }else if(!strcmp_case(category,  "_PHASING_MIR") && ncat>0){
                if(!strcmp_case(item,"entry_id") || !strcmp_case(item,"method")
                   || !strcmp_case(item,"details")){
                    replace_first_str(tmp,"_PHASING_MIR","_phasing_MAD",str);
                }else{
                    replace_first_str(tmp,"_PHASING_MIR.","_phasing_MAD.pdbx_",str);
                }
                
            }else if(!strcmp_case(category, "_PHASING_MIR_DER_SITE")&& ncat>0){
                replace_first_str(tmp,"_PHASING_MIR_DER_SITE",
                                  "_pdbx_phasing_MAD_set_site",str);
                if(!strcmp_case(item, "der_id")){
                    replace_first_str(tmp,"_PHASING_MIR_DER_SITE.der_id",
                                      "_pdbx_phasing_MAD_set_site.set_id",str);
                    
                }else if(!strcmp_case(item, "Occupancy_anom")){
                    replace_first_str(tmp,"_phasing_MIR_der_site.Occupancy_anom",
                                      "_pdbx_phasing_MAD_set_site.Occupancy",str);
                    
                }else if(!strcmp_case(item, "Occupancy_anom_esd")){
                    replace_first_str(tmp,"_phasing_MIR_der_site.occupancy_anom_esd",
                                      "_pdbx_phasing_MAD_set_site.occupancy_esd",str);
                }
                
            }else if(!strcmp_case(category,"_PHASING_MIR_DER") && ncat>0){
                replace_first_str(tmp,"_PHASING_MIR_DER",
                                  "_pdbx_phasing_MAD_set",str);
                
                if(!strcmp_case(item, "Reflns_anomalous")){
                    replace_first_str(tmp,"_phasing_MIR_der.Reflns_anomalous",
                                      "_pdbx_phasing_MAD_set.Reflns",str);
                    
                }else if(!strcmp_case(item, "R_cullis_anomalous")){
                    replace_first_str(tmp,"_phasing_MIR_der.R_cullis_anomalous",
                                      "_pdbx_phasing_MAD_set.R_cullis",str);
                }
            }
            if(strstr(str,"\n"))
                fprintf(fout, "%s", str);
            else
                fprintf(fout, "%s\n", str);
        }
    }
        
    fclose(fp);
   
}



void CCP4_ref_refmac5(FILE *fout, char *inpfile, char *file_format,char *method)
/* assign the files (from refinement) to different subroutines */
{
    char str[512],tmp[512], category[100],item[100];
    int k=0;
    
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) 
        open_file_error(inpfile,"CCP4_ref_refmac5");

    if(strstr(file_format, "PDB"))        
       pdb_2_cif(fout, inpfile);
    
    else if (strstr(file_format, "CIF")) {

        if( is_cif(inpfile)< 5) {
            printf("The input file (%s) for refmac5 is not in mmCIF format",inpfile);
            return;
        }
//        nline=num_of_line(inpfile);
//        line=new char *[nline];
        
        k=0;
        while (fgets(str, sizeof str, fp) != NULL) {
            
            rid_of_front_space(str);
            if(str[0] !='#') k++;
            if(k==1 && !strncmp_case(str,"data_",5)) continue;
            
            check_category(str, category, item);
            if(strlen(category)>0 && strlen(item)>0 ){
                if(!strcmp_case(category, "_refine")) continue; 
                if((!strcmp_case(category, "_entry") ||
                    !strcmp_case(category, "_diffrn"))
                    && !strcmp_case(item, "id")) continue; 
                if(!strcmp_case(category, "_audit")
                    && !strcmp_case(item, "creation_date")) continue; 
                     
                if(strstr(category,"_ccp4_refine_tls")){
                    strcpy(tmp, strstr(str, "tls")+3 );
                    strcpy(str, "_pdbx_refine_tls");
                    strcat(str, tmp);
                    
                }else if(!strcmp_case(category,"_refine_ls_restr_ncs")&&
                   !strncmp_case(item,"ccp4",4)){
                    strcpy(tmp, strstr(str, "ccp4")+4 );
                    strcpy(str, "_refine_ls_restr_ncs.pdbx");
                    strcat(str, tmp);
                }else if(!strcmp_case(category,"_struct_ncs_dom_lim")&&
                   !strncmp_case(item,"ccp4",4)){
                    
                    strcpy(tmp, strstr(str, "ccp4")+4 );
                    strcpy(str, "_struct_ncs_dom_lim.pdbx");
                    strcat(str, tmp);
                }else if(!strcmp_case(category,"_refine_ls_shell")&&
                   !strcmp_case(item,"R_factor_R_all")){
                    
                    strcpy(str,"_refine_ls_shell.R_factor_all\n");
                }
            }
            convert_restr_refmac5_cif(str);
            
            strstr(str,"\n") ?  fprintf(fout,"%s", str ) : fprintf(fout,"%s\n", str );
        }
        fprintf(fout,"\n#\n");
        rewind(fp);

        

        while (fgets(str, sizeof str, fp) != NULL) { //only _refine.
            check_category(str, category, item);
            if(strlen(category)>0 && strlen(item)>0 &&
               !strcmp_case(category,"_refine") ){
                strcpy(tmp,str);
                
                if (!strcmp_case(item,"B_iso_mean")){
                    refine.B_iso_mean = get_float(tmp, "B_iso_mean","\n");

                        /*
                }else if(!strcmp_case(item,"ls_matrix_type") && strchr(str, "\"")){
                    refine.ls_matrix_type = get_substr(str, "\"","\"");
                }else if (!strcmp_case(item,"ls_matrix_type") && strchr(tmp, "'")){
                    refine.ls_matrix_type = get_substr(str, "'","'");
                    
                }else if (!strcmp_case(item,"solvent_model_details")){
                    refine.solvent_model_details = get_substr(tmp, "'","'");
                        */
                    
                }else if (!strcmp_case(item,"aniso_B[1][1]")){
                    refine.aniso_B11 = get_float(tmp, "aniso_B[1][1]","\n");
                    
                }else if (!strcmp_case(item,"aniso_B[2][2]")){
                    refine.aniso_B22 = get_float(tmp, "aniso_B[2][2]","\n");
                    
                }else if (!strcmp_case(item,"aniso_B[3][3]")){
                    refine.aniso_B33 = get_float(tmp, "aniso_B[3][3]","\n");
                    
                }else if (!strcmp_case(item,"aniso_B[1][2]")){
                    refine.aniso_B12 = get_float(tmp, "aniso_B[1][2]","\n");
                    
                }else if (!strcmp_case(item,"aniso_B[1][3]")){
                    refine.aniso_B13 = get_float(tmp, "aniso_B[1][3]","\n");
                    
                }else if (!strcmp_case(item,"aniso_B[2][3]")){
                    refine.aniso_B23 = get_float(tmp, "aniso_B[2][3]","\n");
                    
                }else if (!strcmp_case(item,"solvent_vdw_probe_radii")){
                    refine.pdbx_solvent_vdw_probe_radii = get_float(tmp, "solvent_vdw_probe_radii","\n");
                    
                }else if (!strcmp_case(item,"solvent_ion_probe_radii")){
                    refine.pdbx_solvent_ion_probe_radii = get_float(tmp, "solvent_ion_probe_radii","\n");
                    
                }else if (!strcmp_case(item,"solvent_shrinkage_radii")){
                    refine.pdbx_solvent_shrinkage_radii = get_float(tmp, "solvent_shrinkage_radii","\n");
                    
                }else if (!strcmp_case(item,"ls_d_res_high")){
                    refine.ls_d_res_high = get_float(tmp, "ls_d_res_high","\n");
                    
                }else if (!strcmp_case(item,"ls_d_res_low")){
                    refine.ls_d_res_low = get_float(tmp, "ls_d_res_low","\n");
                    
                }else if (!strcmp_case(item,"ls_R_factor_R_work")){
                    refine.ls_R_factor_R_work = get_float(tmp, "ls_R_factor_R_work","\n");
                    
                }else if (!strcmp_case(item,"")){
                    refine.ls_R_factor_R_free = get_float(tmp, "ls_R_factor_R_free","\n");
                    
                }else if (!strcmp_case(item,"ls_R_factor_R_all")){
                    refine.ls_R_factor_all = get_float(tmp, "ls_R_factor_R_all","\n");
                    
                }else if (!strcmp_case(item,"ls_wR_factor_R_work")){
                    refine.ls_wR_factor_R_work = get_float(tmp, "ls_wR_factor_R_work","\n");
                    
                }else if (!strcmp_case(item,"ls_wR_factor_R_free")){
                    refine.ls_wR_factor_R_free = get_float(tmp, "ls_wR_factor_R_free","\n");
                    
                }else if (!strcmp_case(item,"ls_percent_reflns_obs")){
                    refine.ls_percent_reflns_obs = get_float(tmp, "ls_percent_reflns_obs","\n");
                    
                }else if (!strcmp_case(item,"ls_percent_reflns_R_free")){
                    refine.ls_percent_reflns_R_free = get_float(tmp, "ls_percent_reflns_R_free","\n");
                    
                }else if (!strcmp_case(item,"correlation_coeff_Fo_to_Fc")){
                    refine.correlation_coeff_Fo_to_Fc = get_float(tmp, "correlation_coeff_Fo_to_Fc","\n");
                }else if(!strcmp_case(item,"ls_Correlation_coeff_Fo_to_Fc")){
                    refine.correlation_coeff_Fo_to_Fc = get_float(tmp,"ls_Correlation_coeff_Fo_to_Fc", "\n");
                    
                }else if (!strcmp_case(item,"correlation_coeff_Fo_to_Fc_free")){
                    refine.correlation_coeff_Fo_to_Fc_free = get_float(tmp, "correlation_coeff_Fo_to_Fc_free","\n");
                }else if (!strcmp_case(item,"ls_Correlation_coeff_Fo_to_Fc_free")){
                    refine.correlation_coeff_Fo_to_Fc_free = get_float(tmp, "ls_Correlation_coeff_Fo_to_Fc_free","\n");


                    
                }else if (!strcmp_case(item,"pdbx_overall_ESU_R")){
                    refine.pdbx_overall_ESU_R = get_float(tmp, "pdbx_overall_ESU_R","\n");
                    
                }else if (!strcmp_case(item,"pdbx_overall_ESU_R_Free")){
                    refine.pdbx_overall_ESU_R_Free = get_float(tmp, "pdbx_overall_ESU_R_Free","\n");


                    
                }else if (!strcmp_case(item,"pdbx_overall_ESU_ML")){
                    refine.overall_SU_ML = get_float(tmp, "pdbx_overall_ESU_ML","\n");
                }else if (!strcmp_case(item,"ls_Overall_ESU_ML")){
                    refine.overall_SU_ML = get_float(tmp, "ls_Overall_ESU_ML","\n");

                    
                }else if (!strcmp_case(item,"pdbx_overall_ESU_B")){
                    refine.overall_SU_B = get_float(tmp, "pdbx_overall_ESU_B","\n");
                }else if (!strcmp_case(item,"ls_Overall_ESU_B")){
                    refine.overall_SU_B = get_float(tmp, "ls_Overall_ESU_B","\n");
                    
                }else if (!strcmp_case(item,"ls_number_reflns_R_work")){
                    refine.ls_number_reflns_R_work = get_int(tmp, "ls_number_reflns_R_work","\n");
                    

                }else if (!strcmp_case(item,"ls_number_reflns_R_free")){
                    refine.ls_number_reflns_R_free = get_int(tmp, "ls_number_reflns_R_free","\n");
                    
                }else if (!strcmp_case(item,"ls_number_reflns_obs")){
                    refine.ls_number_reflns_obs = get_int(tmp, "ls_number_reflns_obs","\n");


                }else if(!strcmp_case(item,"ls_Overall_ESU_Rfree")){
                    refine.pdbx_overall_ESU_R_Free = get_float(tmp,"ls_Overall_ESU_Rfree", "\n");   
                }
            }
    
        }
        
    }else if(strstr(file_format, "LOG")) {
        printf("REFMAC5 produce a CIF file containing statistics. Please give\n");
        printf("the file name (use option -iCIF file_name).\n");
        fclose(fp);
        return;
    }
    fclose(fp);
    
}

void convert_restr_refmac5_cif(char *str)
{
    char *param, stand[40], tmp[60], *str_old=NULL;
    int i;
    
    static const char *refmac_cif_28[] = {
        
"r_bond_refined_d         ,\"Bond distances: refined atoms           \",,", 
"r_bond_other_d           ,\"Bond distances: others                  \",,",  
"r_angle_refined_deg      ,\"Bond angles  : refined atoms            \",,",  
"r_angle_other_deg        ,\"Bond angles  : others                   \",,",  
"r_dihedral_angle_1_deg   ,\"Torsion angles, period  1. refined      \",,",  
"r_dihedral_angle_2_deg   ,\"Torsion angles, period  2. refined      \",,",  
"r_dihedral_angle_3_deg   ,\"Torsion angles, period  3. refined      \",,",  
"r_dihedral_angle_4_deg   ,\"Torsion angles, period  4. refined      \",,",  
"r_chiral_restr           ,\"Chiral centres: refined atoms           \",,",  
"r_gen_planes_refined     ,\"Planar groups: refined atoms            \",,",  
"r_gen_planes_other       ,\"Planar groups: others                   \",,",  
"r_nbd_refined            ,\"VDW repulsions: refined atoms           \",,",  
"r_nbd_other              ,\"VDW repulsions: others                  \",,",  
"r_nbtor_refined          ,\"VDW; torsion: refined atoms             \",,",  
"r_nbtor_other            ,\"VDW; torsion: others                    \",,",  
"r_xyhbond_nbd_refined    ,\"HBOND: refined atoms                    \",,",  
"r_symmetry_vdw_refined   ,\"VDW repulsions; symmetry: refined atoms \",,",  
"r_symmetry_vdw_other     ,\"VDW repulsions; symmetry: others        \",,",  
"r_symmetry_hbond_refined ,\"HBOND; symmetry: refined atoms          \",,",  
"r_symmetry_hbond_other   ,\"HBOND; symmetry: others                 \",,",  
"r_mcbond_it              ,\"M. chain bond B values: refined atoms   \",,",  
"r_mcbond_other           ,\"M. chain bond B values: others          \",,",  
"r_mcangle_it             ,\"M. chain angle B values: refined atoms  \",,",  
"r_mcangle_other          ,\"M. chain angle B values: others         \",,",  
"r_scbond_it              ,\"S. chain bond B values: refined atoms   \",,",  
"r_scbond_other           ,\"S. chain bond B values: others          \",,",  
"r_scangle_it             ,\"S. chain angle B values: refined atoms  \",,",  
"r_scangle_other          ,\"S. chain angle B values: others         \",,"   
    };
    
    str_old=str;
    for(i=0;i<28;i++){
        if(sscanf(refmac_cif_28[i], "%s", stand) != 1 ) continue;
        strcpy(tmp , refmac_cif_28[i] + strlen(stand)+1);
        param = get_substr(tmp, ",", ",,");
        if(strstr_case(str, param)){
            replace_first_str(str_old, param, stand, str);
            break;
        }
    }
 
}
void CCP4_ref_restrain(FILE *fout, char inpfile[], char *file_format,
                          char method[])
/* assign the files (from refinement) to different subroutines */
{
    char str[512], tmp[512];
    int k;
    
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s (routine:CCP4_ref_restrain)\n",inpfile);
        return;
    }

    if(strstr(file_format, "PDB")){
        pdb_2_cif(fout,  inpfile);
    
    }else if (strstr(file_format, "CIF")) {
        if( is_cif(inpfile)< 5) {
            printf("The input file (%s) for restrain is not in mmCIF format",inpfile);
            return;
        }
        
        k=0;
        while (fgets(str, sizeof str, fp) != NULL) {  
            strcpy(tmp, str);
            rid_of_front_space(tmp);
            if(tmp[0] !='#') k++;
            if(k==1 && !strncmp_case(tmp,"data_",5)) continue;
            fprintf(fout,"%s", str );
        }
    }else if(strstr(file_format, "LOG")) {
        printf("RESTRAIN produce a CIF file containing statistics. Please\n");
        printf("give the file name (use option -iCIF file_name).\n");
        return;
    }
    fclose(fp);
    
}
/*
void CCP4_ref_restrain_log(FILE *fout, char inpfile[], char method[])
{

}
*/


void CCP4_phasing_DM(FILE *fout, char *inpfile,char *format,char *method)
/* extract the information.   FOM after density modification. 
*/
{
    FILE *fp;

    int  n=0, nref=0, m=0;
    char str[256], juck[80];
    float resol_L, resol_H,  fm, phi;
    char *method1=NULL, *method2=NULL,meth[256], *tmp=NULL;
    float nf, a1,a2,a3,a4,a5;
    
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_phasing_DM)\n",inpfile);
        return;
    }
    
    if(!strcmp_case(format, "CIF") || !strcmp_case(format, "PDB")){
        write_cif_or_pdb(fout,  inpfile, format,method);
        return;
    }
   
    while (fgets(str, sizeof str, fp) != NULL) {
        upperstr(str);
        if(strstr_case(str, "<li> Solvent flattening")){
            method1 = (char *)"Solvent flattening ";
            
        }else if(strstr_case(str, "<li> Histogram matching")){
            method2 = (char *)"Histogram matching";
            
        }else if(strstr_case(str, "Number of reflections included in phase recombination =")){
            pdbx_phasing_dm.reflns = get_int(str,"= ", "\n");

        }else if(strstr_case(str, "Auto Wang-radius")){
            pdbx_phasing_dm.mask_radius = get_int(str,"Wang-radius", "\n");
            
        }else if(pattern5(str, "Effective resolution:"," A", "","","")){
            pdbx_phasing_dm.d_res_high = get_float(str,":", "A");
            
            
        }else if(strstr_case(str, "% of cell   Min Rho   Max Rho   Mean Rho   Std.Dev.")){
            
            while (fgets(str, sizeof str, fp) != NULL){
                if(strstr_case(str,"Protein:")){
                    tmp= strstr(str,":")+1;
                    
                    m=sscanf(tmp, "%f%f%f%f%f\n", &a1,  &a2,  &a3,  &a4,  &a5);
                    if(m==5){
                        pdbx_phasing_dm.protein_percent_sol = a1;
                        pdbx_phasing_dm.protein_min_density = a2;
                        pdbx_phasing_dm.protein_max_density = a3;
                        pdbx_phasing_dm.protein_mean_density = a4;
                        pdbx_phasing_dm.protein_mean_density_esd = a5;
                    }
                } else if(strstr_case(str,"Solvent:")){
                    tmp= strstr(str,":")+1;
                    
                    m=sscanf(tmp, "%f%f%f%f%f\n", &a1,  &a2,  &a3,  &a4,  &a5);
                    if(m==5){
                        pdbx_phasing_dm.solvent_percent_sol = a1;
                        pdbx_phasing_dm.solvent_min_density = a2;
                        pdbx_phasing_dm.solvent_max_density = a3;
                        pdbx_phasing_dm.solvent_mean_density = a4;
                        pdbx_phasing_dm.solvent_mean_density_esd = a5;
                    }
                }else
                    break;               
            }
            
        }else if (strstr_space(str,"RMIN - RMAX  S^2  NREFLS  SIGMAA MEAN FOM")>0){
            
            n=0;
            while (fgets(str, sizeof str, fp) != NULL){
                upperstr(str);
                if(!is_space_line(str))continue;
                if(strstr(str, "------") || strstr(str, "CYCLE") || strlen(str)<20 )break;
                if(strstr_space(str, "(calc) (comb)") >0 ) continue;
                if(sscanf(str, "%f %f %s %f   %s %s %s %f %f  %s %s",
                          &resol_L, &resol_H, juck, &nf , juck, juck,juck,
                          &fm,&phi, juck,juck)==11){
                    nref=(int) nf;
                    pdbx_phasing_dm_shell.d_res_low[n] = resol_L;
                    pdbx_phasing_dm_shell.d_res_high[n] = resol_H;
                    pdbx_phasing_dm_shell.reflns[n] = nref;
                    pdbx_phasing_dm_shell.fom[n] = fm;
                    pdbx_phasing_dm_shell.delta_phi_final[n] = phi;
                    
                    n++;
                    if(n>=NBIN-1){
                        printf("Warning! No DM statistics will be written\n");
                        n=0;
                        break;
                    }
                    
                }
            }
        }
    }
    pdbx_phasing_dm_shell.number_bin = n;
    
    if(method1 && method2){
        strcpy(meth,method1);
        strcat(meth, " and ");
        strcat(meth, method2);
        strcpy(pdbx_phasing_dm.method , meth);
    }else if(method1 && !method2){
        strcpy(pdbx_phasing_dm.method , method1);
    }else if(!method1 && method2){
        strcpy(pdbx_phasing_dm.method , method2);
    }

    fclose(fp);  
    
}

void CCP4_phasing_SOLOMON(FILE *fout, char *inpfile,  char *format,char *method)
/* extract the information.   FOM after density modification. */
{
    FILE *fp;

    int i, j=0, nc=0, nline=0, nb1,nb2,refl_c[NBIN], refl_a[NBIN], nref, m, n, ncol=0;
    char str[512],charact, **fomlines, tmp[80];
    float resL_c[NBIN],resH_c[NBIN],fom_c[NBIN],resL_a[NBIN],resH_a[NBIN],fom_a[NBIN];
    float fom, a;
    

    fomlines = set_memory_2d(500,300);
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_phasing_SOLOMON)\n",inpfile);
        return;
    }
    
    if(!strcmp_case(format, "CIF") || !strcmp_case(format, "PDB")){
        write_cif_or_pdb(fout,  inpfile, format,method);
        return;
    }

    
    while (fgets(str, sizeof str, fp) != NULL) {
        upperstr(str);
        nc=0;        
        if (strstr_space(str, "Reflections with Combined Phase Information")>0){
            
            while (fgets(str, sizeof str, fp) != NULL){
                upperstr(str);
                strcpy(fomlines[nc], str);
                nc++;
                ncol = nc;
                
                if(nc>=500){
                    printf("Warning! The log file for SOLOMON  may be wrong!!\n");
                    return;
                }
                if(strstr_space(str, "Mean Variation of Information")>0){
                    nline=nc;
                    break;
                }
                
            }
            
        }else if(strstr_space(str,"Overall Figures of Merit")){
            n=0;
            while (fgets(str, sizeof str, fp) != NULL){
                if(n++>10 || strstr_case(str, "HEADER INFORMATION") ||
                  strstr_case(str,"Title") )break;
                
                m=sscanf(str, "%s%d%f",tmp, &nref, &fom);
                if(m==3){
                    if(!strcmp_case(tmp, "CENTRIC")){
                        pdbx_phasing_dm.reflns_centric = nref;
                        pdbx_phasing_dm.fom_centric = fom;
                       
                    }else if(!strcmp_case(tmp, "NON-CENTRIC")){
                        pdbx_phasing_dm.reflns_acentric = nref;
                        pdbx_phasing_dm.fom_acentric = fom;
                        
                    }else if(!strcmp_case(tmp, "TOTAL")){
                        pdbx_phasing_dm.reflns = nref;
                        pdbx_phasing_dm.fom = fom;
                        break;
                        
                    }
                }
            }
                       
        }else if(strstr_space(str,"new solvdens:")){
            n=sscanf(strstr_case(str, ":") +1 ,"%f", &a);
            if(n==1)pdbx_phasing_dm.solvent_mean_density = a;
            
        }else if(strstr_space(str,"mean density of protein:")){
            n=sscanf(strstr_case(str, ":") +1 ,"%f", &a);
            if(n==1)pdbx_phasing_dm.protein_mean_density = a;
            
        }else if(strstr_space(str,"sd of protein:")){
            n=sscanf(strstr_case(str, ":") +1 ,"%f", &a);
            if(n==1)pdbx_phasing_dm.protein_mean_density_esd = a;
            
        }
        
    }
    
    charact='-';
    nb1=0;
    for(i=0; i<nline; i++){/* for Centric DATA */
        strcpy(str,fomlines[i]);
        
        if(strstr(str, "--")){
            char2space(str, charact); /*subsitute charact by space*/
            if(sscanf(str, "%f %f %d %f",
                   &resL_c[nb1],&resH_c[nb1], &refl_c[nb1], &fom_c[nb1]) != 4)
                continue;
            nb1++;
            if(nb1>=NBIN-1){
                printf("Warning! The log file for SOLOMON  may be wrong!!\n");
                return;
            }
            
        }
        if(strstr(str, "NON-CENTRIC")){
            j=i;
            break;
        }
    }
    
    nb2=0;
    for(i=j; i<nline; i++){/* for Non-Centric DATA */
        strcpy(str,fomlines[i]);
        if(strstr(str, "--")){
            char2space(str, charact); 
            if(sscanf(str, "%f %f %d %f",
                   &resL_a[nb2],&resH_a[nb2], &refl_a[nb2], &fom_a[nb2]) !=4 )
                continue;
            nb2++;
            if(nb2>=NBIN-1){
                printf("Warning! The log file for SOLOMON  may be wrong!!\n");
                return;
            }
        }
    }

    if(fomlines) free_memory_2d(fomlines, ncol);
    
    if(nb1==nb2 && nb1>0){
        pdbx_phasing_dm_shell.number_bin=nb1;
        for(i=0; i<nb1; i++){
            pdbx_phasing_dm_shell.d_res_low[i] = resL_c[i];
            pdbx_phasing_dm_shell.d_res_high[i]=resH_c[i];
            pdbx_phasing_dm_shell.reflns_centric[i]=refl_c[i];
            pdbx_phasing_dm_shell.fom_centric[i]= fom_c[i];
            pdbx_phasing_dm_shell.reflns_acentric[i]=refl_a[i];
            pdbx_phasing_dm_shell.fom_acentric[i]=fom_a[i];
        } 
    }
    fclose(fp);
}

void CCP4_amore(FILE *fout, char *inpfile,char *format, char *method)
        /* extract things from Amore */
{
    char str[512], tmp[256];
    int n=0, m=0;
    float cc_F, r_fact, cc_I, cc_F_tmp, r_fact_tmp, cc_I_tmp,resL,resH;
    float a1,a2,a3,a4,a5,a6;
    
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_amore)\n",inpfile);
        return;
    }
    
    while (fgets(str, sizeof str, fp) != NULL) {
        if(strstr_space(str, "** ROTATION FUNCTION REQUESTED **")){
            while (fgets(str, sizeof str, fp) != NULL) {
                if(strstr_space(str,"Resolution limits are:")){
                    strcpy(tmp,strstr(str,"are:")+4);
                    n=sscanf(tmp,"%f%f", &resL,&resH);
                    if(n==2){
                        pdbx_phasing_MR.d_res_high_rotation = resH;
                        pdbx_phasing_MR.d_res_low_rotation = resL;
                    }
                    break;
                }
            }
           
        }else if(strstr_space(str, "** TRANSLATION FUNCTION REQUESTED **")){
            
            cc_F=0;
            r_fact=0;
            cc_I=0;

            while (fgets(str, sizeof str, fp) != NULL) {
                if(strstr_space(str,"Resolution limits are:")){
                    strcpy(tmp,strstr_case(str,"are:")+4);
                    n=sscanf(tmp,"%f%f", &resL,&resH);
                    if(n==2){
                        pdbx_phasing_MR.d_res_high_translation = resH;
                        pdbx_phasing_MR.d_res_low_translation = resL;
                    }
                }else if(strstr_space(str," TABLE   Alpha    Beta   Gamma    Tx      Ty      Tz Corr_F Rfac Corr_I Pkcount  Dmin")){
                   
                    while (fgets(str, sizeof str, fp) != NULL) {
                        if (is_space_line(str) ==0) continue;
                        if(pattern5(str, "SOLUTIONTF", ".", ".", ".", ".")){
                           n=sscanf(str,"%*s%d %f%f%f %f%f%f %f%f%f", &m,
                                    &a1,&a2,&a3, &a4,&a5,&a6,      
                                    &cc_F_tmp, &r_fact_tmp, &cc_I_tmp);
                           if(n==10 && m>0){
                               if(cc_F_tmp>cc_F) {
                                   pdbx_phasing_MR.angle_alpha = a1;
                                   pdbx_phasing_MR.angle_beta = a2;
                                   pdbx_phasing_MR.angle_gamma = a3;
                                   pdbx_phasing_MR.fract_x = a4;
                                   pdbx_phasing_MR.fract_y = a5;
                                   pdbx_phasing_MR.fract_z = a6;
                                   
                                   cc_I = cc_I_tmp;
                                   cc_F = cc_F_tmp;
                                   r_fact = r_fact_tmp;
                                   
                                   if(cc_F>0)pdbx_phasing_MR.correlation_coeff_Fo_to_Fc = cc_F;
                                   if(cc_I>0)pdbx_phasing_MR.correlation_coeff_Io_to_Ic = cc_I;  
                                   if(r_fact>0)pdbx_phasing_MR.R_factor = r_fact;
                               }
                           }
                           break;
                       }
                    }
                } 
                        
            }
            
        }else if(strstr_space(str, "** RIGID BODY FITTING FUNCTION REQUESTED **")){
            cc_F=0;
            r_fact=0;
            cc_I=0;
            
            while (fgets(str, sizeof str, fp) != NULL) {
                if(strstr_space(str,"Resolution limits are:")){
                    strcpy(tmp,strstr_case(str,"are:")+4);
                    n=sscanf(tmp,"%f%f", &resL,&resH);
                    if(n==2){
                        pdbx_phasing_MR.d_res_high_fit = resH;
                        pdbx_phasing_MR.d_res_low_fit = resL;
                    }
                }else if(strstr_space(str," TABLE   Alpha    Beta   Gamma    Tx      Ty      Tz Corr_F Rfac Corr_I Pkcount")){
                   
                    while (fgets(str, sizeof str, fp) != NULL) {
                        if (is_space_line(str) ==0) continue;
                        if(pattern5(str, "SOLUTIONF", ".", ".", ".", ".")){
                           n=sscanf(str,"%*s%d %f%f%f %f%f%f %f%f%f", &m,
                                    &a1,&a2,&a3, &a4,&a5,&a6,      
                                    &cc_F_tmp, &r_fact_tmp, &cc_I_tmp);
                           if(n==10 && m>0){
                               if(cc_F_tmp>cc_F) {
                                   pdbx_phasing_MR.angle_alpha = a1;
                                   pdbx_phasing_MR.angle_beta = a2;
                                   pdbx_phasing_MR.angle_gamma = a3;
                                   pdbx_phasing_MR.fract_x = a4;
                                   pdbx_phasing_MR.fract_y = a5;
                                   pdbx_phasing_MR.fract_z = a6;
                                   
                                   cc_I = cc_I_tmp;
                                   cc_F = cc_F_tmp;
                                   r_fact = r_fact_tmp;
                                   
                                   if(cc_F>0)pdbx_phasing_MR.correlation_coeff_Fo_to_Fc = cc_F;
                                   if(cc_I>0)pdbx_phasing_MR.correlation_coeff_Io_to_Ic = cc_I;  
                                   if(r_fact>0)pdbx_phasing_MR.R_rigid_body = r_fact;
                               } 
                           }
                           break;
                        }
                    }
                    
                } 
                        
            }
        }
        
    }

    fclose(fp);

    
    
}


void CCP4_phaser(FILE *fout, char *inpfile,char *format, char *method)
        /* extract things from Amore */
{
    char str[512], tmp[512];
    int n=0;
    float a1,a2,a3,resL,resH;
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s(routine:CCP4_amore)\n",inpfile);
        return;
    }
    

    while (fgets(str, sizeof str, fp) != NULL) {
        if(strstr_space(str," Resolution:")){
                    
            n=sscanf(strstr(str,":")+1,"%f%f", &resH,&resL);
            if(n==2){
                pdbx_phasing_MR.d_res_high_translation = resH;
                pdbx_phasing_MR.d_res_low_translation = resL;
            }else if(n==1){
                pdbx_phasing_MR.d_res_high_translation = resH;
            }
                    
        }else if(pattern5(str,"SOLU 6DIM ", " EULER", ".", ".", "FRAC" )){
            get_data_set_id(str, "EULER", "FRAC", tmp);
            
            n=sscanf(tmp,"%f%f%f",  &a1,&a2,&a3);
            
            if(n==3){
                pdbx_phasing_MR.angle_alpha = a1;
                pdbx_phasing_MR.angle_beta = a2;
                pdbx_phasing_MR.angle_gamma = a3;
            }
            
            get_data_set_id(str,  "FRAC","\n", tmp);
            n=sscanf(tmp,"%f%f%f",  &a1,&a2,&a3);
            
            if(n==3){
                pdbx_phasing_MR.fract_x = a1;
                pdbx_phasing_MR.fract_y = a2;
                pdbx_phasing_MR.fract_z = a3;
                                   
            }

            break;
            
            
        }
    }
    fclose(fp);
    
}

void CCP4_molrep(FILE *fout, char *inpfile,char *format, char *method)
        /* extract things from Amore */
{
    char str[512], tmp[256];
    int n=0;
    float cc_F=0, r_fact=0,cc_F_tmp=0, r_fact_tmp=0,resL=0,resH=0;
    float a1,a2,a3,a4,a5,a6;
    
    FILE *fp;
    
    if((fp = fopen(inpfile, "r"))==NULL) 
        open_file_error(inpfile, "CCP4_molrep");
        
    while (fgets(str, sizeof str, fp) != NULL) {
        if(strstr_space(str,"Sol_--- Rotation function ---")){
            while (fgets(str, sizeof str, fp) != NULL) {
                if(pattern5(str, "Sol_ Resmin,Resmax           :" ,"","", "","")){
                    strcpy(tmp,strstr(str,":")+1);
                    n=sscanf(tmp,"%f%f", &resL,&resH);
                    if(n==2){
                        pdbx_phasing_MR.d_res_high_rotation = resH ;
                        pdbx_phasing_MR.d_res_low_rotation = resL ;
                    }
                    break;
                }
            
            }
        }else if(strstr_space(str,"Sol_--- Translation function ---")){
            
            while (fgets(str, sizeof str, fp) != NULL) {
                if(pattern5(str, "sol_", "Resmin", "Resmax", ":", "")){
                    strcpy(tmp,strstr(str,":")+1);
                    n=sscanf(tmp,"%f%f", &resL,&resH);
                    if(n==2){
                        pdbx_phasing_MR.d_res_high_translation = resH;
                        pdbx_phasing_MR.d_res_low_translation = resL;
                    }
                    break;
                }
            
            }
        }else if(pattern5(str, "sol_", "_Rf_", "_Tf_", "", "") ||
                 pattern5(str, "sol_Mon_", "_Rf_",  "_Tf_"," ", "") ){
            n=sscanf(str,"%*s %f%f%f %f%f%f %f%f", 
                     &a1,&a2,&a3, &a4,&a5,&a6, &r_fact_tmp, &cc_F_tmp);
             
            if(n==8){
                if(cc_F_tmp>cc_F) {
                    cc_F = cc_F_tmp;
                    r_fact = r_fact_tmp;
                    pdbx_phasing_MR.correlation_coeff_Fo_to_Fc = cc_F;
                    pdbx_phasing_MR.R_factor = r_fact;
                    
                    pdbx_phasing_MR.angle_alpha = a1;
                    pdbx_phasing_MR.angle_beta = a2;
                    pdbx_phasing_MR.angle_gamma = a3;
                    pdbx_phasing_MR.fract_x = a4;
                    pdbx_phasing_MR.fract_y = a5;
                    pdbx_phasing_MR.fract_z = a6;
                    
                }
            }
        }
    }
    fclose(fp);
    
     
}

    
