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

#include "set.h"
#include "glva.h"

#define KAKAKU 19  

double jh_kaite(int); 

void econ(void){
	FILE *ifp;
	double dtemp[7];
	int num_dtemp;
	char rec[MAX_REC_LEN+1];
	int k;
	
	double kaite_hp; 
	double kaite_ci;  
	
	num_dtemp = sizeof dtemp / sizeof dtemp[0];
	for(k=0; k<ECEDY-ECSTY+1; k++){
		Id_Hhd[k] = 1.;
		Id_Cid[k] = 1.;
	}
	
	
	ifp = ifp_econ;
	k = 1; 
	while(fgets(rec, MAX_REC_LEN, ifp)!=NULL){
		rd_drec(rec, dtemp, num_dtemp);
		if( k!=(int)dtemp[0]){
			printf("Econの年度が違います。(%d<>%d)\n", k, (int)dtemp[0]);
			exit(1);
		}else{
			Ri[k-ECSTY] = dtemp[1]/100.;
			H[k-ECSTY]  = dtemp[5]/100.;
			Ci[k-ECSTY] = dtemp[6]/100.;
			
			Ri2[k-ECSTY] = pow(1.+Ri[k-ECSTY], 0.5) - 1.;	
		}
		k++;
	}
	while(k<=ECEDY){
		Ri[k-ECSTY] = Ri[k-1-ECSTY];
		H[k-ECSTY]  = H[k-1-ECSTY];
		Ci[k-ECSTY] = Ci[k-1-ECSTY];
		
		Ri2[k-ECSTY] = Ri2[k-1-ECSTY];
		k++;
	}
	
	

	
	Id_Hhd[5-ECSTY] = 1.;
	
	for(k=6; k<=ECEDY; k++){
		if(k<21){
			kaite_ci = nround(Ci[k-2-ECSTY], 3);
			kaite_hp = nround((1.0+kaite_ci) * nround(1.0+jh_kaite(k-1),3), 3) - 1.;
			if(k<=7) kaite_hp = kaite_ci;
			if(k==18) kaite_hp = -0.009;
			
			Id_Hhd[k-ECSTY] = nround(Id_Hhd[k-1-ECSTY] * (1.0 + kaite_hp), 3);
		} else {
			kaite_ci = Ci[k-2-ECSTY];
			kaite_hp = (1.0+kaite_ci) * (1.0+jh_kaite(k-1)) - 1.;  
			
			Id_Hhd[k-ECSTY] = Id_Hhd[k-1-ECSTY] * (1.0 + kaite_hp);
		}
		
		if(k>19){
			Id_Cid[k-ECSTY] = Id_Cid[k-1-ECSTY] * (1. + Ci[k-1-ECSTY]);
		}
	}
	
	
	dtemp[0] = Id_Hhd[KAKAKU-ECSTY];
	if(dtemp[0] > 0.){
		for(k=ECSTY; k<=ECEDY; k++) Id_Hhd[k-ECSTY] /= dtemp[0];
	} else {
		printf("保険料改定率(%f)、価格基準年度(%d)の設定がおかしいです\n", dtemp[0], KAKAKU);
		exit(1);
	}
	
}


double jh_kaite(int k){
	double djh;
	int n;
	
	if(k<=4 || ECEDY<k){
		printf("econ.c中のjh_kaite()の引数年度が想定範囲外です。\n");
		exit(1);
	}else{
		djh = 1.;
		for(n=2; n<=4; n++){
	 		djh *= (1. + H[k-n-ECSTY]) / (1. + Ci[k-n-ECSTY]);
	 	}
	 	djh = pow(djh, 1. / 3.) - 1.;
	}
	return(djh);
}

