#include <stdio.h>

/************************************************
 * solution for CS 2073, homework 6.
 * 
 * problem description refers to 
 * http://www.cs.utsa.edu/~korkmaz/teaching/cs2073/assign/hw-06.pdf
 *
**/

int main(){
    // file pointer, variable for input data file
    FILE *inFile ;
    
    // file pointer, variable for otuput data file
    FILE *outFile ;
    
    // upper bound and lower bound of I
    int UI, LI;
    // upper bound and lower bound of J
    int UJ, LJ;
    
    // check whether we can read the input file.
    if((inFile = fopen("data.txt","r"))==NULL){
        printf("Error in opening the data file\n");
        exit(1);
    }
    
    // check whether we can open the file to be written.
    if((outFile= fopen("result.txt","w"))==NULL){
        printf("Error in opening the output file\n");
        exit(1);
    }
    
    // variables to control the for loop 
    int i ,j, k;
    
    // variable for the result
    float total = 0; 
    
    
    for(i = 1;i<=10;i++){
          total = 0;
          
          // read data from the input file
          fscanf(inFile,"%d %d %d %d", &LI, &UI, &LJ, &UJ);
          
          // print them in the output file
          fprintf(outFile,"%d %d %d %d\n",LI,UI, LJ, UJ);

          // check the data validation, they should be greater than zero
          if( UI <=0 || LI <=0 || UJ <=0 || LJ <=0){
              fprintf(outFile,"Invalid input data.\n");
              fprintf(outFile,"Please make sure the input data are greater than 0.\n\n");
              continue;
          }else if (UI<LI || UJ < LJ ){
          // check the data validation, the upper bound should be greater than the lower bound
              fprintf(outFile,"Invalid input data.\n");
              fprintf(outFile,"Please make sure UI > LI and UJ > LJ.\n\n");  
              continue;                
          }else{
          // calculate the total sum                
              for(j = LI;j<=UI;j++){
                    for (k = LJ;k<=UJ;k++){
                        total = total + (float)(j+k)/(j*k); 
                    }
              }          
          // write the calculation result into the output file
              fprintf(outFile,"Total = %lf\n\n",total);
          }            
    }
/*    system("pause"); */
    return 0;
}
















