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

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

#define KAKAKU 14  /* 2014(H26)年度価格 */

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.;
	}
	
	
	/*** econの読み込み ***/
	ifp = ifp_econ;
	k = 1;  /* econファイルの初期年度 */
	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++;
	}
	
	Ci[1-ECSTY] = -0.7/100.;
	/*** econ読み込み終了 ***/
	
	if(Flg_Rima>0){
		for(k=MAX(ECSTY,Rima_Yr_Str); k<=MIN(ECEDY, Rima_Yr_End); k++){
			Ri[k-ECSTY] += Drima;
			Ri2[k-ECSTY] = pow(1.+Ri[k-ECSTY], 0.5) - 1.;
		}
	}
	
	/*** 保険料改定率の初期値セット ***/
	Id_Hhd[5-ECSTY] = 1.;
	
	for(k=6; k<=ECEDY; k++){
		/** 2006年度以降の保険料改定率作成(本来分) **/
		if(k<17){
			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;
			
			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>14){
			Id_Cid[k-ECSTY] = Id_Cid[k-1-ECSTY] * (1. + Ci[k-1-ECSTY]);
		}
	}
	
	
	/*** H26年度価格に変換 ***/
	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);
}

