#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <dos.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAXMEANS 20  /* base 1 not 0 */

/* calculate time to appearance of symptoms and AUDPC */

/* Ignore all that you were taught about using local variables.  All the compilers
   out there can't handle a small amount of stack data, and will cause a stack overflow */

int dplants[MAXMEANS+1];
char tempstr[81], location[21], genotype[21];
char descrstr[81], outfilname[69], infilname[69];
int daydate[MAXMEANS+1], plants[MAXMEANS+1];

main()
{
   double ratio, t50pctincidence;
   int c, i, ndates, year, plotno, rep, nplants, ok, solved, temp, missingdatacase;
   int dplants50, dlowdate, dhighdate, ddiffdate; 
   FILE *outfilptr, *infilptr;
   int stack=60000; /* cannot prevent stack overflow in Large model, use DOS386X */
    
   for(i=1;i<=25;i++) printf("\n");
   printf("       ***  CalcIP6.EXE: Calculate Time to Appearance of Disease Symptoms\n");
   printf("	      Mark Burow, Dec. 7, 2019\n");
   printf("	      Calculates time to appearance of symptoms in 50 percent of plants\n");
   printf("       Written in C for the Zortech C 3.0 compiler\n");
   printf("       Program (16 bit) requires 8088 or higher CPU, 256KB RAM,\n");
   printf("       DOS 6.0 or higher, one disk drive\n\n\n");
   printf("       Data format:\n");
   printf("         header: NDates, date1, date2, ..., daten\n");
   printf("         per data case: Year Location$ Plotno Genotype Rep NPlants nplantsi\n");
   printf("         NDates, date1, date2, ... , daten\n");
   printf("         Use -9999 as missing data, Append -8888 as last line of file\n");
   
   /* open file */
    ok=FALSE;
    while(ok==FALSE)
    {   
        printf("What is the name of the input file:\n");
        gets((char *) infilname);
        infilptr=fopen((char *) infilname, "r"); /* see if exists */
        if(infilptr==NULL)
        {
            printf("Cannot open the file.  Type any key to continue.\n");
            c=getch();
        }
        else ok=TRUE;
    }
 
   /* open outputfile */
    ok=FALSE;
    while(ok==FALSE)
    {
        printf("What should be the name of the output file:\n");
        gets((char *) outfilname);
   
        outfilptr=fopen((char *) outfilname, "r"); /* see if exists */
        if(outfilptr!=NULL) fclose(outfilptr);
        /* file already exists, so don't overwrite.
         * Closing file will make ptr NULL so
         * will have to cycle again */
        else outfilptr=fopen((char *) outfilname, "w");

        if(outfilptr==NULL)
        {
            printf("Cannot open the file.  Type any key to continue.\n");
            c=getch();
        }
        else ok=TRUE;
    }
    
    /* print header */
    fprintf(outfilptr, "       ***  CalcIP6.EXE: Calculate Time to Appearance of Disease Symptoms ***\n");
    fprintf(outfilptr, "       Mark Burow, Dec. 7, 2019\n");
    fprintf(outfilptr, "       Calculates time to appearance of symptoms in 50 percent of plants\n\n");

    /* Initialize matrices */
    for(i=0;i<=MAXMEANS;i++)
    {
        daydate[i]=0;
        plants[i]=0;
        dplants[i]=0.0;
    }

    /* get data */
    printf("Enter a one-line description of the data:\n");
    fflush(stdin);
    gets(descrstr);

    /* read disk file */
    /* NDates, date1, date2, ... , daten */	
    /* Year Location$ Plotno Genotype Rep NPlants nplantsi */

    printf("This data set is described as:\n");
    printf("     %s\n", descrstr);
    fprintf(outfilptr, "\nThis data set is described as %s:\n", descrstr);
	
    fscanf(infilptr, "%d", &temp); 
    ndates=temp; 

    printf("There are %d dates when ratings were taken.  These were:\n", ndates);
    fprintf(outfilptr, "There are %d dates when ratings were taken.  These were:\n", ndates);
    for(i=1; i<=ndates; i++)
    {
        fscanf(infilptr,"%d ", &temp);
        daydate[i]=temp;
        printf(" %d ", daydate[i]);
        fprintf(outfilptr, " %d ", daydate[i]);
    }
    printf("\n");
    fprintf(outfilptr, "\n\n");

    fprintf(outfilptr, "year location             plotno genotype             rep nplts ");
    for(i=1; i<=ndates; i++)
    {
        if(i<ndates) fprintf(outfilptr, "t%d   ", i);
        else if(i==ndates) fprintf(outfilptr, "t%d  ", i); /* one space short so next item prints over column start */
    }
    printf("\n");
    fprintf(outfilptr, "timeto50pctinfection\n");

    while(year!=-8888) /* append -8888 at EOF */	
    {	/* read in data for this plot */
        missingdatacase=FALSE;
        fscanf(infilptr, "%d", &year);
        if(year==-8888) break;  /* seems to be necessary to get out of the loop and end the program */
        fscanf(infilptr,"%s ", location);
        fscanf(infilptr, "%d ", &plotno);
        fscanf(infilptr, "%s ", genotype);
        fscanf(infilptr, "%d ", &rep);		
        fscanf(infilptr, "%d ", &nplants);
	
        for(i=1; i<=ndates; i++)
        {
            plants[i]=0;	/* reset from previous line */
            fscanf(infilptr,"%d ", &temp);
            plants[i]=temp;
            if(temp == -9999) missingdatacase=TRUE; /* do not correct for FALSE - any miss means whole case bad */
        }
        printf("\n");
	
        /* calculate time to 50% infection */
        /* double all nplants to keep as integers - because 50% infection is diving by 2 - */
        /* and avoid rounding errors, halve at end */
		
        if(missingdatacase==TRUE) goto skipcase;
        for(i=1;i<=ndates;i++)
        {
            dplants[i] = 2 * plants[i];
        }
            dplants50 = nplants;	/* because was not divided by 2 */
	
        /* reset t50pctincidence for this plot */
        t50pctincidence = 0.0;
	
        solved=FALSE;
        if(dplants50<dplants[1]) /* earliest rating date was too late */
        {
            t50pctincidence = (double) daydate[1];  /* assign earliest rating date */
            solved=TRUE;
        }	
        else if(dplants50>dplants[ndates]) /* latest rating date was too early */
        {
            t50pctincidence = (double) daydate[ndates];  /* assign latest rating date */
            solved=TRUE;
        }	
        /* firstpass: see if 50% incidence occurs exactly on one of the scoring dates */
        /* perhaps use else if here instead */
        if(solved==FALSE)
        {
            for(i=1;i<=ndates;i++)
            {
                if (dplants50==dplants[i])
                {
                    t50pctincidence = (double) daydate[i];
                    solved=TRUE;
                }
            }
	
            /* second pass: must interpolate if did not fall exactly on a date */
            while(solved==FALSE)
            {
                for(i=1; i<ndates; i++)
                {
                    if((dplants50>dplants[i]) && (dplants50<dplants[i+1]))
                    {
                        /* value lies between these two */
                        dlowdate = 2 * daydate[i];
                        dhighdate = 2 * daydate[i+1];
                        ddiffdate = dhighdate - dlowdate;
                        ratio = ((double) (dplants50 - dplants[i])) / ((double) (dplants[i+1] - dplants[i]));
                        t50pctincidence =  0.50 * (double) (dlowdate + ratio * ddiffdate);		
                        solved=TRUE;
                    }
                }
            }
        }
		
        /* print results to file */
        /* Year Location$ Plotno Genotype$ Rep NPlants plantsi date50*/	
        skipcase: /* skipped calculation, print data then notify of missing data */
        fprintf(outfilptr, "%4d %-20s %6d %-20s %2d %4d ", year, &location, plotno, &genotype, rep, nplants);
        for(i=1; i<=ndates; i++)
        {
            fprintf (outfilptr, "%4d ", plants[i]);
        }
       if(missingdatacase==FALSE) fprintf(outfilptr, "%6.2f\n", t50pctincidence);
        else fprintf(outfilptr, "missingdata\n");
        fflush(outfilptr);	
    }
	
    printf("Finished with analysis. Press any key to continue\n");
    c=getch();
	
    fclose(infilptr);
    fclose(outfilptr);   
    exit(0);
}

/* ============== END OF PROGRAM ===================== */

