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

typedef struct Range
{
    float rec_min;
    float rec_max;
} range;

typedef struct Dati
{
    char cognome[41];
    char nome[41];
    int podi;
    float record;
    int giorno;
    int mese;
    int anno;
} dati;

int main(int argc, char *argv[])
{
    FILE *fa, *fp;
    range v[100];
    dati x;
    int i=0, j, podi_min=10000, podi_max=0, flag=0;
    int anno=0, mese=0, giorno=0;

    if(argc!=2)
    {
        printf("Usage: %s filename\n", argv[0]);
        return -1;
    }

    fp=fopen("filter.txt", "r");

    if(fp==NULL)
    {
        printf("Errore nell'apertura del file filter.txt\n");
        return -2;
    }

    while(fscanf(fp, "%f %*c %f", &v[i].rec_min, &v[i].rec_max)!= EOF)
    {
        i++;
    }
    fclose(fp);

    fa=fopen(argv[1], "r");

    if(fa==NULL)
    {
        printf("Errore nell'apertura del file %s", argv[1]);
        return -3;
    }

    printf("      Nome     Cognome\t Podi\tRecord\t   Data\n");

    while(fscanf(fa,"%s %s %d %f %d/%d/%d", x.nome, x.cognome, &x.podi, &x.record, &x.giorno, &x.mese, &x.anno)!=EOF)
    {
        for(j=0; j<i; j++)
        {
            if(x.record>v[j].rec_min && x.record<v[j].rec_max)
                flag=1;
        }

        if(flag!=1)
            printf("%10s %10s %6d %9.2f %5d/%d/%d\n", x.nome, x.cognome, x.podi, x.record, x.giorno,
                   x.mese, x.anno);

        if(podi_min>x.podi)
            podi_min=x.podi;

        if(podi_max<x.podi)
            podi_max=x.podi;

        if(anno<x.anno)
        {
            anno=x.anno;
            if(mese<x.mese)
            {
                mese=x.mese;
                if(giorno<x.giorno)
                {
                    giorno=x.giorno;
                }

            }

        }
        flag=0;
    }


    fclose(fa);


fa=fopen(argv[1], "r");

if(fa==NULL)
{
    printf("Errore nell'apertura del file %s", argv[1]);
    return -5;
}

printf("\n");

while(fscanf(fa,"%s %s %d %f %d/%d/%d", x.nome, x.cognome, &x.podi, &x.record, &x.giorno, &x.mese, &x.anno)!=EOF)
{

    if(x.podi==podi_min)
        printf("Podi min: %d %s %s\n", x.podi, x.nome, x.cognome);

    if(x.podi==podi_max)
        printf("Podi max: %d %s %s\n", x.podi, x.nome, x.cognome);

    if(anno==x.anno && mese==x.mese)
    printf("Podio piu' recente: %s %s %d/%d/%d\n", x.nome, x.cognome, x.giorno, x.mese, x.anno);

}

fclose(fa);

return 0;
}
