/*
FILE:     pdb_extract_sf.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 gather all the reflection data and convert it to
   cif format.   March, 2002
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include "CifFileObj.h"
#include "sf.h"
#include "util.h"

void merge_I_F(int argc, char **argv);

int main(int argc, char *argv[])
{    
    char outfile[MAXL], init_ID[40], ref_ID[40];
    int i;
    FILE *fout;
    
    
/*merge I and F in one data set from two files  */ 
    for(i=1; i<argc; i++){
        if(!strcmp_case(argv[i], "-merge") ){
            //pdb_extract_sf -merge -icif fine_name (special)
            merge_I_F(argc, argv);
            exit(0);  
        }else if(!strcmp_case(argv[i],"-o")){
            strcpy(outfile, argv[i+1]);            
        }else if(!strcmp_case(argv[i],"-dt")){
            strcpy(init_ID, argv[i+1]);
        }else if(!strcmp_case(argv[i],"-rt")){
            strcpy(ref_ID, argv[i+1]);
        }
        
    }
   
    check_input_error(argc, argv, outfile, init_ID, ref_ID);
    if(strlen(outfile)<=0) strcpy(outfile,"pdb_extract_sf.mmcif");
    
    fout = fopen(outfile, "w");

/*Extracting  reflections for refinement*/
    if(!strcmp_case(ref_ID, "-RP") ){
        fprintf(fout,"\ndata_set1_for_refinement\n");
        write_refl_refine(fout, argc, argv);
    }
    
/*Extracting reflections from initial data processing */
    if(!strcmp_case(init_ID, "-DP") ){
        fprintf(fout,"\ndata_set2_for_phasing\n");
        write_refl_initial(fout, argc, argv);
    }

   
/*Extracting imgCIF header */
//    write_refl_imgcif(fout, argc, argv);
    
    if( num_of_line(outfile)<200 ){
        printf("\nThe output file (%s) is suspicious!\n",outfile);
        printf("Please check the supported version of pdb_extract_sf or the input format.\n");
        return 0;
    }
    
    if(fout) fclose(fout);
    printf("\nChecking and rewriting the mmCIF file (%s)\n",outfile);
    cifparse(outfile);

    printf("\nThe output file name:  %s\n\n", outfile);
    
    exit(0);      
}


void check_input_error(int argc,char **argv, char *outfile,char *init_ID,
                       char *ref_ID)
/* obtaining the needed information and error messages*/
{
    int i=0, dp=0, dt=0, dlog=0,  rp=0, rt=0, r1=0, r2=0 ;
    static char *prog=(char *)"HKL, SCALEPACK, DTREK, SAINT, 3DSCALE, SCALA, CNS, OTHER";
    static char *prog_ref=(char *)"REFMAC5, SHELX, TNT, HKL, SCALEPACK, DTREK, SAINT, 3DSCALE, SCALA, CNS, XPREP,OTHER";
    static char *log=(char *)"-IDAT, -ICIF,  -ILOG";
    static char *option=(char *)"-rt, -rp, -dt, -dp, -c, -w, -IDAT, -ICIF, -ILOG, -o -merge";
   
    
    
    if(argc<=1 || !strcmp_case(argv[1],"-H")|| !strcmp_case(argv[1],"-HELP")){
        usage();
    }
    
    strcpy(outfile, "");
    strcpy(init_ID, "");
    strcpy(ref_ID, "");
    
    for(i=1; i<argc; i++){
        if(argv[i-1][0] =='-' && argv[i][0]=='-'){
            printf("\nInput wrong! Check arguments (%s) and (%s).\n",
                   argv[i-1],argv[i]);
            printf("Only options are allowed to start with (-)!\n\n");
            usage();
        }
        
        if(argv[i][0] =='-'){
            if(!strstr_case(option, argv[i])){
                printf("\nInput was wrong!\n");
                printf("You provided wrong option [%s]\n", argv[i]);
                printf("Option should be one of [%s]\n", option);
                usage();
            }
            if(i==argc-1){
                printf("\nInput was wrong!\n");
                printf("The option [%s] should be followed by a file name\n", argv[i]);
                usage();
            }  
        }

        if(!strcmp_case(argv[i-1], "-o")){
            strcpy(outfile, argv[i]);
        }
    }
    if(strlen(outfile)<=0) strcpy(outfile, "pdb_extract_sf.mmcif");
    
            
/* for initial data proccess */
    for(i=1; i<argc; i++){    
        if(!strcmp_case(argv[i], "-DP")){
            
            dp++;
            if(!strstr_case(prog, argv[i+1])){
                printf("\nInput is wrong after argument [-DP].\n"); 
                printf("Input (%s) is not one of (%s).\n", argv[i+1], prog);
                printf("(Note):\nIf program name is not shown above, \n");
                printf("please give 'OTHER', then provide either a CIF file\n");
                printf("or a plain text file with H,K,L,I(F),sigmaF(sigmaI) seperated by a space.\n");
                printf("The command will be 'pdb_extract_sf -dt ? -dp OTHER -c ? -w ? -idat file_name'.\n\n");
                usage();
            }
            
       }else if(!strcmp_case(argv[i],"-DT")){
            if(argc-i<2){
                printf("\nNo input after [%s  %s]!\n",argv[i-1], argv[i]);
                printf("Please provide the correct data type (I or F) after -DT.\n");
                printf("It is normally I (intensity) after data reduction.\n\n");
                usage();
            }
            
           
            dt++;
            
            if( strcmp_case(argv[i+1], "I")  && strcmp_case(argv[i+1], "F") ){
                printf("\nInput argument is wrong after [-DT].\n"); 
                printf("Please provide correct data type (I or F) after -DT.\n");
                printf("It is normally I (intensity) after data reduction.\n\n");
                usage();     
            }
            
        }else if(!strcmp_case(argv[i],"-C")){
            if(argc-i<6) {
                printf("\nNo enough arguments after [%s and %s]!\n", argv[i-1], argv[i]);
                printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together\n");
                exit(0);
            }

            if(strcmp_case(argv[i+2], "-W")){ 
                printf("\nInput is wrong after arguments [%s %s]!\n", argv[i], argv[i+1]);
                printf("Please provide the option [-W] after %s\n", argv[i+1]);
                printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together.\n");
                usage();                
            }else {
                if(!strstr_case(log,argv[i+4]) ){
                    printf("\nInput is wrong after arguments [%s %s]!\n", argv[i+2], argv[i+3]);
                    printf("Please provide one of the options [%s] after %s.\n", log,argv[i+3]);
                    printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together.\n");
                    usage();  
                }else{
                    if(!argv[i+5]){
                        printf("\nInput is wrong after arguments [%s %s %s ]!\n",
                               argv[i+2], argv[i+3], argv[i+4]);
                        printf("Please provide a file name after [%s].\n", argv[i+4]);
                        printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together.\n");
                        usage();
                    } else{
                        dlog++;
                    }
                }
            }
        }else if(!strcmp_case(argv[i],"-W")){
            if(argc-i<4) {
                printf("\nNo enough arguments after [%s and %s]!\n", argv[i-1], argv[i]);
                printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together\n");
                exit(0);
            }
            if(strncmp_case(argv[i+2],"-I", 2)){
                printf("Note: '-c ? -w ? -idat (or -ilog, -icif) ?' should be together.\n");
                exit(0); 
            }
            
            
        }
    }
        

//    printf("whis is data = %d %d\n", dt, dp);
    
    if(dp>1 || dt>1 ){
        printf("\nInput wrong! You entered -DT or -DP more than once.\n"); 
        printf("Command should be '-DT ? -DP ? -C ? -W ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(dp==1 && dt!=1){
        printf("\nInput wrong! You used option [-DP], but no -DT option.\n"); 
        printf("Command should be '-DT ? -DP ? -C ? -W ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(dt==1 && dp!=1){
        printf("\nInput wrong! You used option [-DT], but no -DP option.\n"); 
        printf("Command should be '-DT ? -DP ? -C ? -W ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(dt==1 && dp==1 && dlog<=0){
        printf("\nInput wrong! There is no '-C i -W j'  option (for initial data process)\n"); 
        printf("Command should be '-DT ? -DP ? -C ? -W ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(dt==1 && dp==1 && dlog>0){
        strcpy(init_ID, "-DP");      
    }
    
        

/* for final refinament */             


    for(i=1; i<argc-1; i++){
        if( !strcmp_case(argv[i],"-RT") ){
            if(!strcmp_case(argv[i+1], "I") || !strcmp_case(argv[i+1], "F") ){
                rt++;
            }else{
                printf("\nInput wrong after argument [-RT]! \n");
                printf("Please provide correct data type (F or I) after -RT.\n");
                printf("Normally, I for SHELX, F for CNS and TNT.\n");
                usage();
            }
        }
        
        if( !strcmp_case(argv[i],"-RP") ){
            if(strstr_case(prog_ref,argv[i+1])) {
                rp++;
            }else{

                printf("\nInput (%s) is wrong!\n",argv[i+1]);
                printf("Please provide correct program name for final refinement\n");
                printf("If program name is not one of (%s), give OTHER!\n", prog_ref);
                
                printf("If the structure factor is in MTZ format, convert it to mmcif format\n");
                printf("(Note: if given OTHER, you must either provide a CIF file\n");
                printf( "or a text file with H, K, L, F(I), sigmaF(sigmaI) seperated by a space.\n");
                printf("The command will be -rp OTHER -icif file_name (if CIF format)\n");
                printf("or -rp OTHER -idat file_name (if free format as mentioned above).)\n");
                usage();    
            }
            
        }
        if(i<argc-2 && (!strcmp_case(argv[i],"-RT") && !strcmp_case(argv[i+2],"-RP")) ||
           (!strcmp_case(argv[i],"-RP") && !strcmp_case(argv[i+2],"-RT"))){
            r1++;
        }
        
        if(i<argc-2 && (!strcmp_case(argv[i],"-RT") || !strcmp_case(argv[i],"-RP")) &&
           (!strcmp_case(argv[i+2],"-idat") || !strcmp_case(argv[i+2],"-icif"))){
            r2++;
        }
        
    }
        
        
    if(rp>1 || rt>1 ){
        printf("\nInput wrong! You entered -RT or -RP more than once.\n\n"); 
        printf("Command should be '-RT ? -RP ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(rp==1 && rt!=1){
        printf("\nInput wrong! There is no -RT option\n\n"); 
        printf("Command should be '-RT ? -RP ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    if(rt==1 && rp!=1){
        printf("\nInput wrong! There is no -RP option\n\n"); 
        printf("Command should be '-RT ? -RP ? -idat ? -ilog ?'.\n\n"); 
        usage();
    }
    
    if(rt==1 && rp==1){
        strcpy(ref_ID, "-RP");
        
        if(r2<=0){
            printf("\nInput wrong! \n"); 
            printf("The right input should be ( -rt ? -rp ?  -idat ?)\n"); 
            usage();
        }
    }
}



/*****************  extracting headers of image CIF file   ****************/
void write_refl_imgcif(FILE *fout, int argc, char **argv)
{
    int i=0;
    char infile[MAXL];
    
    for(i=1; i<argc-1; i++){  
        if(argv[i][0] =='-' && toupper(argv[i][1]) =='I' && 
           toupper(argv[i][2]) =='M' && toupper(argv[i][3])=='G' ){
            
            if(argv[i+1][0] !='-'){
                strcpy(infile, argv[i+1]);
                read_imgCIF_header(fout, infile);
                break;
            } else{ 
                printf("\nInput wrong!!\n");
                printf("The option (-imgCIF) should be followed by filename!\n");
                printf("The filename! (%s) should not be started with (-)!\n", argv[i+1]);
                usage();           
            }      
        }
    }
    
}

void read_imgCIF_header(FILE *fout, char *inpfile)
{
    char str[512];
    FILE *fp;
    
    printf("\nimgCIF file_name: %s\n", inpfile);
    
    if((fp = fopen(inpfile, "r"))==NULL) {        
        printf("Can not open the file %s\n",inpfile);
        return;
    }
    while (fgets(str, sizeof str, fp) != NULL) {
        if(strstr(str, "###_END_OF_HEADER")
           ||strstr(str, "CIF-BINARY-FORMAT-SECTION") )break;   
            
        fprintf(fout,"%s", str);
    }
    fclose(fp);
}

        

void cifparse(char *iFile)
{
  char *diags=NULL, oFile[256];
  CifFileObj * fobjR = NULL;
//  int len=0; 

  strcpy(oFile, iFile);
  
  fobjR = new CifFileObj("", WRITE_MODE, 80, "?", 0);
  fobjR->Read(iFile,diags);
  
//  len =  strlen(diags);
// if (diags) printf(" Diagnostics [ %d  %s] \n", len, diags );
 if (diags) printf(" Diagnostics [ %s] \n", diags );
  
  fobjR->Write(oFile,1);
  fobjR->CloseFile(1);
  if (fobjR) delete fobjR;
  
//  if (iFile) free(iFile);
//  if (oFile) free(oFile);
}

void usage()
{
    printf("------------------------------------------------------\n");
    printf("usage:    pdb_extract_sf [OPTION]... [FILE]...\n\n");
    printf(" -o  followed by the given output file name\n");
    printf("-dt  followed by data type (I or F) after data reduction.\n");
    printf("-dp  followed by program for processing data(HKL|SCALEPACK|DTREK|SAINT|SCALA|3DSCALE|OTHER ).\n");
    printf(" -c  followed by crystal number (like -c 1 ).\n");
    printf(" -w  followed by wavelength number (like -w 1).\n");
    
    printf("-rt  followed by data type used for final refinement (I or F).\n");
    printf("-rp  followed by reflection data format used for final refinement(CNS|TNT|SHELX).\n");
    printf("     (CNS|TNT|SHELX|HKL|SCALEPACK|DTREK|SAINT|SCALA|3DSCALE|OTHER)\n");
    printf("-iDAT  followed by a file name containing reflection data.\n");    
    printf("       (Format corresponds to each program used).\n");    
    printf("-iCIF  followed by a file name containing reflection data or statistics.\n");    
    printf("       The format is in mmcif (see http://pdb.rutgers.edu/mmcif/).\n");
    printf("-iLOG  followed by a LOG file name containing statistics only.\n");    
    printf("       (Format corresponds to each program used).\n\n");    
    printf("Examples:\n");
    printf("To convert reflection data (2 data sets after data reduction) to cif format:\n");
    printf("pdb_extract_sf -o output -dt I -dp HKL -c 1 -w 1 -iDAT name1.sca  -iLOG \n");
    printf("               name1.log -c 1 -w 2 -iDAT name2.sca  -iLOG name2.log\n\n");
    
    printf("To convert reflection data (used for final refinement) to cif format:\n");
    printf("pdb_extract_sf -o output -rt F -rp CNS -iDAT name1.hkl \n\n");
    
    exit(0);
}

    
void write_data_type_head(FILE *fout, char *I_F_type)
/* write the data head */
{
    
    if(!strcmp_case(I_F_type,"F")){

        fprintf(fout, "\n#reflection data type is amplitude.\n\n");
        fprintf(fout, "loop_\n");
        fprintf(fout, " _refln.crystal_id \n");
        fprintf(fout, " _refln.wavelength_id \n");
        fprintf(fout, " _refln.scale_group_code\n");
        fprintf(fout, " _refln.index_h\n");
        fprintf(fout, " _refln.index_k\n");
        fprintf(fout, " _refln.index_l\n");
        fprintf(fout, " _refln.F_meas_au\n" );
        fprintf(fout, " _refln.F_meas_sigma_au \n" );
        fprintf(fout, " _refln.status\n" );
        
    }else if(!strcmp_case(I_F_type,"I")){  
        fprintf(fout, "\n\n# reflection data type is intensity\n\n" );
        fprintf(fout, "loop_\n");
        fprintf(fout, " _refln.crystal_id \n");
        fprintf(fout, " _refln.wavelength_id \n");
        fprintf(fout, " _refln.scale_group_code\n");
        fprintf(fout, " _refln.index_h\n");
        fprintf(fout, " _refln.index_k\n");
        fprintf(fout, " _refln.index_l\n");
        fprintf(fout, " _refln.intensity_meas\n" );
        fprintf(fout, " _refln.intensity_sigma\n" );
        fprintf(fout, " _refln.status\n" );

    }
    else{
        printf("Data-type (%s) is wrong! (It should be either (F) or (I))\n",
               I_F_type );
        exit(0);
    }
}


void merge_I_F(int argc, char **argv)
//merge two data sets in one file (I and F) into one mmCIF category
//pdb_extract_sf -merge -icif fine_name
{
    char  iFile[512], outfile[512];
    char *diags=NULL, *blockId=NULL, *fnx=(char *)"cif2cif_from_cifparse";
    char **H1, **K1, **L1, **H2, **K2, **L2 , **status1, **status2;
    char **Fo_au1, **sFo_au1, **Io1, **sIo1, **Fo_au2, **sFo_au2, **Io2, **sIo2;
    long n1, n2,n, i, j;
    FILE *fout, *fp;
    
    strcpy(outfile, "");
    for(i=1; i<argc-1; i++){
        if(!strcmp_case(argv[i], "-o") ){
            strcpy(outfile,argv[i+1]);
        }else if (!strcmp_case(argv[i], "-icif") ){
            strcpy(iFile,argv[i+1]);
        }
    }
    
    if(strlen(outfile)<=0) strcpy(outfile, "pdb_extract_sf.mmcif");
    
    fout = fopen(outfile, "w");
    if(strlen(iFile)<=0) {
        printf("\nError! Input file does not exist! \n");
        exit(0);
    }

    CifFileObj * fobjR = NULL;
    fp = fopen(iFile, "r");
    if(fp==NULL){
        open_file_error(iFile, "merge_I_F");
    }
    
    fobjR = new CifFileObj(fnx, WRITE_MODE, 80, "?", 1);
    fobjR->Read(iFile,diags);
    if (diags != NULL) fprintf(stderr, "Diags for file %s: %s\n",iFile,diags);
    fobjR->CloseFile();
    if (fobjR) delete fobjR;

    fobjR = new CifFileObj(fnx, READ_MODE);
    blockId = fobjR->GetBlockName(0);
    
    printf("blockid1= %s\n", blockId);
   
    H1 = get_attribute_values(fobjR, blockId, "refln", "index_h", &n1);
    K1 = get_attribute_values(fobjR, blockId, "refln", "index_k", &n1);
    L1 = get_attribute_values(fobjR, blockId, "refln", "index_l", &n1);
    
    Fo_au1 = get_attribute_values(fobjR, blockId, "refln", "F_meas_au", &n1);
    sFo_au1 = get_attribute_values(fobjR, blockId, "refln", "F_meas_sigma_au", &n1);

    Io1 = get_attribute_values(fobjR, blockId, "refln", "intensity_meas", &n1);
    sIo1 = get_attribute_values(fobjR, blockId, "refln", "intensity_sigma", &n1);
    
    status1 = get_attribute_values(fobjR, blockId, "refln", "status", &n1);
    
    printf("Number of reflections   n1 = %ld\n\n", n1);

    if(! fobjR->GetBlockName(1)){
        printf("\nError! The file does not have the second block!\n");
        exit(0);
    }
       
    blockId = fobjR->GetBlockName(1); //second block
    printf("blockid2= %s\n", blockId);

    H2 = get_attribute_values(fobjR, blockId, "refln", "index_h", &n2);
    K2 = get_attribute_values(fobjR, blockId, "refln", "index_k", &n2);
    L2 = get_attribute_values(fobjR, blockId, "refln", "index_l", &n2);
    
    Fo_au2 = get_attribute_values(fobjR, blockId, "refln", "F_meas_au", &n2);
    sFo_au2 = get_attribute_values(fobjR, blockId, "refln", "F_meas_sigma_au", &n2);

    Io2 = get_attribute_values(fobjR, blockId, "refln", "intensity_meas", &n2);
    sIo2 = get_attribute_values(fobjR, blockId, "refln", "intensity_sigma", &n2);

    status2 = get_attribute_values(fobjR, blockId, "refln", "status", &n2);
    printf("Number of reflections  n2 = %ld\n\n", n2);


    
    if(n1>0 && n2>0 &&( Io1 && Fo_au2  || Io2 && Fo_au1)){
        fprintf(fout, "loop_\n");
        fprintf(fout, " _refln.crystal_id\n");
        fprintf(fout, " _refln.wavelength_id\n");
        fprintf(fout, " _refln.scale_group_code\n" );
        fprintf(fout, " _refln.status\n" );
        
        fprintf(fout, " _refln.index_h\n");
        fprintf(fout, " _refln.index_k\n");
        fprintf(fout, " _refln.index_l\n");
        
        fprintf(fout, " _refln.F_meas_au\n");
        fprintf(fout, " _refln.F_meas_sigma_au\n");
        fprintf(fout, " _refln.intensity_meas\n");
        fprintf(fout, " _refln.intensity_sigma\n");
        
        if(Io1 && Fo_au2){ //file2 has F
            printf("Number of reflections for F =  %ld\n", n2);
            
            for(i=0; i<n2; i++){
                fprintf(fout, " 1 1 1  ");
                (status2)? fprintf(fout,"%s ", status2[i]) :  fprintf(fout," ? ");
                fprintf(fout,"%s ", H2[i]) ;
                fprintf(fout,"%s ", K2[i]) ;
                fprintf(fout,"%s ", L2[i]) ;
                fprintf(fout,"%s ", Fo_au2[i]);
                (sFo_au2) ? fprintf(fout,"%s ", sFo_au2[i]) : fprintf(fout," 0 ");
                
                n=0;
                for(j=0; j<n1; j++){
                    if(!strcmp(H2[i], H1[j]) && !strcmp(K2[i], K1[j]) &&
                       !strcmp(L2[i], L1[j])){
                        fprintf(fout," %s ", Io1[j]);
                        (sIo1)? fprintf(fout," %s \n", sIo1[j]) : fprintf(fout," 0 \n");
                        n++;
                        break;
                    }
                }
                if (n==0) fprintf(fout," 0  0 \n");
            }
        }else if (Io2 && Fo_au1){ //file1 has F
            printf("Number of reflections for F =  %ld\n", n1);
            
            for(i=0; i<n1; i++){
                fprintf(fout, " 1 1 1 ");
                (status1[i])? fprintf(fout,"%s ", status1[i]) :  fprintf(fout," ? ");
                fprintf(fout,"%s ", H1[i]) ;
                fprintf(fout,"%s ", K1[i]) ;
                fprintf(fout,"%s ", L1[i]) ;
                fprintf(fout,"%s ", Fo_au1[i]);
                (sFo_au1)? fprintf(fout,"%s ", sFo_au1[i]) : fprintf(fout," 0 ");
                
                n=0;
                for(j=0; j<n2; j++){
                    if(!strcmp(H2[j], H1[i]) && !strcmp(K2[j], K1[i]) && !strcmp(L2[j], L1[i])){
                        fprintf(fout,"%s ",Io2[j]);
                        (sIo2)? fprintf(fout,"%s \n", sIo2[j]) : fprintf(fout," 0 \n");
                        n++;
                        break;
                    }
                }
                if (n==0) fprintf(fout," 0 0 \n");
            }
        }
    }else{
        printf("\nThe two files are not merged! \n");
        printf("One file should have intensity and the other file should have amplitude\n");
        delete_file("cif2cif_from_cifparse");
        exit(0);
    }
        
    delete_file("cif2cif_from_cifparse");
    fclose(fout);
    printf("\nChecking and rewriting the mmCIF file (%s)\n",outfile);
    if(H1) free_memory_2d(H1, n1);
    if(K1) free_memory_2d(K1, n1);
    if(L1) free_memory_2d(L1, n1);
    if(Fo_au1) free_memory_2d(Fo_au1, n1);
    if(sFo_au1) free_memory_2d(sFo_au1, n1);
    if(Io1) free_memory_2d(Io1, n1);
    if(sIo1) free_memory_2d(sIo1, n1);
    if(status1) free_memory_2d(status1, n1);
    
    if(H2) free_memory_2d(H2, n2);
    if(K2) free_memory_2d(K2, n2);
    if(L2) free_memory_2d(L2, n2);
    if(Fo_au2) free_memory_2d(Fo_au2, n2);
    if(sFo_au2) free_memory_2d(sFo_au2, n2);
    if(Io2) free_memory_2d(Io2, n2);
    if(sIo2) free_memory_2d(sIo2, n2);
    if(status2) free_memory_2d(status2, n2);

    
    cifparse(outfile);
}


