if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Source-reading base-R replay; no case/model JSON or earlier numeric results.
args<-commandArgs(FALSE);f<-sub("^--file=","",args[grepl("^--file=",args)]);o<-if(length(f))dirname(normalizePath(f))else getwd();d<-file.path(o,"econ15-sources");w<-file.path(dirname(dirname(o)),"work","textbook-rewrite-2026");a<-file.path(w,"source-audit-econ15");m<-numeric();checks<-0
put<-function(k,v){m[k]<<-as.numeric(v)};frac<-function(s){v<-strsplit(as.character(s),"/",fixed=TRUE)[[1]];if(length(v)==2)as.numeric(v[1])/as.numeric(v[2])else as.numeric(v)};near<-function(x,y)all(abs(x-y)<=1e-11*pmax(1,abs(x),abs(y)));getcsv<-function(n)read.csv(file.path(d,n),colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL,fileEncoding="UTF-8-BOM")
ev<-getcsv("actual-bank-rate-change-events.csv");file<-file.path(a,"BankOfEngland-official-BankRate-history.html")
if(file.exists(file)){
 text<-paste(readLines(file,warn=FALSE,encoding="UTF-8"),collapse="\n");blocks<-regmatches(text,gregexpr("(?si)<tr\\b[^>]*>.*?</tr>",text,perl=TRUE))[[1]];actual<-numeric()
 for(block in blocks){s<-trimws(gsub("[[:space:]]+"," ",gsub("<[^>]+>"," ",block)));parts<-regmatches(s,regexec("^([0-9]{2} [A-Za-z]{3} [0-9]{2}) ([0-9]+\\.[0-9]+)$",s))[[1]];if(length(parts)){day<-format(as.Date(parts[2],"%d %b %y"),"%Y-%m-%d");actual[day]<-as.numeric(parts[3])}}
 stopifnot(all(as.numeric(ev$rate_percent_per_year_source_decimal)==actual[ev$change_date]));ev$rate_percent_per_year_source_decimal<-as.character(actual[ev$change_date]);checks<-checks+nrow(ev)
}else message("BoE public-selection fallback; no live request")
for(i in seq_len(nrow(ev))){rate<-as.numeric(ev$rate_percent_per_year_source_decimal[i]);put(paste0("country_rate_",i-1,"_percent"),rate);stopifnot(near(frac(ev$rate_fraction_per_year_exact[i]),rate/100));checks<-checks+1}
cuts<-as.Date(c("2024-01-01",ev$change_date[startsWith(ev$change_date,"2024")],"2025-01-01"));iv<-getcsv("derived-2024-policy-rate-duration.csv");total<-0;daysTotal<-0
for(i in seq_len(length(cuts)-1)){start<-cuts[i];end<-cuts[i+1];rate<-as.numeric(tail(ev$rate_percent_per_year_source_decimal[as.Date(ev$change_date)<=start],1));days<-as.numeric(end-start);daysTotal<-daysTotal+days;total<-total+rate*days;stopifnot(iv$start_inclusive[i]==as.character(start),iv$end_exclusive[i]==as.character(end));v<-c(calendar_days=days,annual_policy_rate_percent_exact=rate,annual_policy_rate_fraction_exact=rate/100,day_weight_exact=days/366,rate_times_days_percent_year=rate*days);for(k in names(v)){stopifnot(near(frac(iv[[k]][i]),v[k]));checks<-checks+1;put(paste0("country_interval_",i-1,"_",k),v[k])}}
stopifnot(daysTotal==366);put("country_days",daysTotal);put("country_weighted_rate_percent",total/daysTotal);put("hyp_country_simple_actual366_interest_GBP",1000*total/daysTotal/100);rr<-as.numeric(ev$rate_percent_per_year_source_decimal);put("country_2024_change_percentage_points",tail(rr,1)-rr[length(rr)-2]);put("country_2024_relative_change",tail(rr,1)/rr[length(rr)-2]-1)
s<-getcsv("actual9876-person-INTP-missing-preserved.csv");file<-file.path(w,"source-audit-econ13","Census-ACS2024-1year-Delaware-person.zip");fields<-c("STATE","AGEP","PWGTP","ADJINC","INTP","FINTP")
if(file.exists(file)){con<-unz(file,"psam_p10.csv",open="r");rows<-read.csv(con,colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL);close(con);stopifnot(nrow(rows)==nrow(s),identical(s$source_row_id,as.character(seq_len(nrow(rows)))));for(k in fields){stopifnot(identical(rows[[k]],s[[k]]));checks<-checks+nrow(rows)}}else{rows<-s;message("ACS public minimal-field fallback")}
available<-nzchar(rows$INTP);income<-rep(NA_real_,nrow(rows));income[available]<-as.numeric(rows$INTP[available]);adjusted<-income*as.numeric(rows$ADJINC)/1e6;weight<-as.numeric(rows$PWGTP);cats<-ifelse(!available,"unavailable_under15",ifelse(income<0,"negative",ifelse(income==0,"zero","positive")));stopifnot(all((as.numeric(rows$AGEP)<15)==!available),identical(cats,s$income_category));sm<-getcsv("actual-person-income-category-summary.csv")
for(i in seq_len(nrow(sm))){sel<-cats==sm$category[i];v<-c(source_records=sum(sel),person_weight_sum=sum(weight[sel]),allocated_records=sum(rows$FINTP[sel]=="1"));if(sm$category[i]!="unavailable_under15")v<-c(v,adjusted_income_weighted_sum_exact=sum(adjusted[sel]*weight[sel]));for(k in names(v)){stopifnot(near(frac(sm[[k]][i]),v[k]));checks<-checks+1;put(paste0("person_",sm$category[i],"_",k),v[k])}}
stopifnot(all(vapply(s$adjusted_2024_USD_exact[available],frac,numeric(1))==adjusted[available]));checks<-checks+sum(available)
wt<-sum(weight[available]);totalIncome<-sum(adjusted[available]*weight[available]);v<-c(source_records=nrow(rows),available_records=sum(available),available_person_weight=wt,adjusted_income_weighted_total=totalIncome,adjusted_income_weighted_mean=totalIncome/wt,selected_row4_raw=income[4],selected_row4_adjusted=adjusted[4]);for(k in names(v))put(paste0("person_",k),v[k]);selected<-getcsv("actual-selected-source-row4.csv");for(k in fields)stopifnot(selected[[k]]==rows[[k]][4])
st<-getcsv("actual-bank-period-end-stocks.csv");flow<-getcsv("actual-bank-annual-interest-flows.csv");file<-file.path(a,"JPMorganChase-4Q2024-financial-supplement.pdf");labels<-c(cash_and_due_from_banks="Cash and due from banks",deposits_with_banks="Deposits with banks",gross_loans="Loans",allowance_for_loan_losses="Less: Allowance for loan losses",net_loans="Loans, net of allowance for loan losses",total_assets="TOTAL ASSETS",customer_deposits="Deposits",total_liabilities="TOTAL LIABILITIES",total_equity="TOTAL STOCKHOLDERS\u2019 EQUITY",total_liabilities_equity="TOTAL LIABILITIES AND STOCKHOLDERS\u2019 EQUITY")
if(file.exists(file)&&nzchar(Sys.which("pdftotext"))){tmp<-tempfile(fileext=".txt");stopifnot(system2("pdftotext",c("-layout",shQuote(file),shQuote(tmp)))==0);text<-readChar(tmp,file.info(tmp)$size,useBytes=TRUE);unlink(tmp);pages<-strsplit(text,"\f",fixed=TRUE)[[1]];days<-c("2024-12-31","2024-09-30","2024-06-30","2024-03-31","2023-12-31");lines<-strsplit(pages[6],"\n",fixed=TRUE)[[1]]
 pick<-function(lines,label){candidate<-lines[startsWith(trimws(lines),paste0(label," "))];# exact label before two-or-more spaces
 candidate<-candidate[vapply(candidate,function(z)sub("[[:space:]]{2,}.*$","",trimws(z))==label,logical(1))];stopifnot(length(candidate)==1);suffix<-substring(trimws(candidate),nchar(label)+1);as.numeric(gsub(",","",regmatches(suffix,gregexpr("[0-9][0-9,]*(?:\\.[0-9]+)?",suffix,perl=TRUE))[[1]],fixed=TRUE))}
 for(k in names(labels)){values<-pick(lines,labels[k])[1:5];for(i in seq_len(nrow(st))){j<-match(st$period_end[i],days);stopifnot(as.numeric(st[[paste0(k,"_million_USD")]][i])==values[j]);st[[paste0(k,"_million_USD")]][i]<-as.character(values[j]);checks<-checks+1}}
 lines<-strsplit(pages[5],"\n",fixed=TRUE)[[1]];fl<-c(interest_income="Interest income",interest_expense="Interest expense",net_interest_income="Net interest income");for(k in names(fl)){v<-tail(pick(lines,fl[k]),3)[1:2];for(i in seq_len(nrow(flow))){j<-match(as.numeric(flow$year[i]),c(2024,2023));stopifnot(as.numeric(flow[[paste0(k,"_million_USD")]][i])==v[j]);checks<-checks+1}}
}else message("Bank public stock/flow selection fallback")
for(i in seq_len(nrow(st))){v<-setNames(vapply(names(labels),function(k)as.numeric(st[[paste0(k,"_million_USD")]][i]),numeric(1)),names(labels));stopifnot(v["total_assets"]==v["total_liabilities"]+v["total_equity"],v["net_loans"]==v["gross_loans"]-v["allowance_for_loan_losses"]);for(k in names(v))put(paste0("company_",st$period_end[i],"_",k),v[k]);z<-c(loans_to_customer_deposits_exact=unname(v["gross_loans"]/v["customer_deposits"]),book_equity_to_assets_exact=unname(v["total_equity"]/v["total_assets"]));for(k in names(z)){stopifnot(near(frac(st[[k]][i]),z[k]));put(paste0("company_",st$period_end[i],"_",k),z[k])}}
for(i in seq_len(nrow(flow))){v<-setNames(vapply(c("interest_income","interest_expense","net_interest_income"),function(k)as.numeric(flow[[paste0(k,"_million_USD")]][i]),numeric(1)),c("interest_income","interest_expense","net_interest_income"));stopifnot(v[1]-v[2]==v[3]);for(k in names(v))put(paste0("company_",flow$year[i],"_",k),v[k])}
h<-getcsv("assumed-interest-only-principal-scenarios.csv");for(i in seq_len(nrow(h))){v<-800/frac(h$assumed_annual_simple_rate_exact[i]);stopifnot(near(v,frac(h$hypothetical_principal_USD_exact[i])));put(paste0("hyp_principal_",i-1),v)}
h<-getcsv("assumed-compound-discount-scenarios.csv");for(i in seq_len(nrow(h))){n<-as.numeric(h$year[i]);factor<-(1+.04)^n;v<-c(future_value_USD_exact=1000*factor,present_value_of_1000_USD_exact=1000/factor,simple_future_value_USD_exact=1000*(1+.04*n));for(k in names(v)){stopifnot(near(v[k],frac(h[[k]][i])));put(paste0("hyp_compound_",n,"_",k),v[k])}}
h<-getcsv("assumed-real-rate-scenarios.csv");for(i in seq_len(nrow(h))){pi<-frac(h$assumed_inflation_rate_exact[i]);gross<-1.04/(1+pi);v<-c(exact_real_gross_factor=gross,exact_real_net_rate=gross-1,linear_nominal_minus_inflation=.04-pi);for(k in names(v)){stopifnot(near(v[k],frac(h[[k]][i])));put(paste0("hyp_real_",i-1,"_",k),v[k])}}
h<-getcsv("assumed-two-bank-T-account-stages.csv");AR<-200;AL<-800;AD<-900;BR<-300;BL<-700;BD<-900
for(i in seq_len(nrow(h))){if(i==2){AL<-AL+100;AD<-AD+100};if(i==3){AR<-AR-60;AD<-AD-60;BR<-BR+60;BD<-BD+60};if(i==4){AL<-AL-40;AD<-AD-40};stopifnot(AR+AL==AD+100,BR+BL==BD+100);v<-c(A_reserves_CU=AR,A_loans_CU=AL,A_deposits_CU=AD,A_equity_CU=100,B_reserves_CU=BR,B_loans_CU=BL,B_deposits_CU=BD,B_equity_CU=100,system_reserves_CU=AR+BR,system_loans_CU=AL+BL,system_deposits_CU=AD+BD);for(k in names(v)){stopifnot(v[k]==as.numeric(h[[k]][i]));put(paste0("hyp_ledger_",i-1,"_",k),v[k])}}
write.csv(data.frame(metric=names(m),value=sprintf("%.17g",m)),file.path(o,"econ15-r-results.csv"),row.names=FALSE,quote=TRUE);cat("ECON15 base-R:",length(m),"metrics;",checks,"checks\n")
