if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Independent base-R source readers. No case/model/previous-results input.
args<-commandArgs(FALSE);ff<-sub("^--file=","",args[grepl("^--file=",args)]);o<-if(length(ff))dirname(normalizePath(ff))else getwd();d<-file.path(o,"econ13-sources");a<-file.path(dirname(dirname(o)),"work","textbook-rewrite-2026","source-audit-econ13")
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)}
getcsv<-function(n)read.csv(file.path(d,n),colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL)
near<-function(x,y)all(abs(x-y)<=1e-10*pmax(1,abs(x),abs(y)))
periods<-c("annual2024","2023Q4","2024Q1","2024Q2","2024Q3","2024Q4");keys<-c("gdp","consumption","investment","exports","imports","government","gdi","income_receipts_rest_world","income_payments_rest_world","gnp");pg<-c(9,9,9,10,10,10,10,10,10,10);ln<-c(1,2,26,44,47,50,62,69,70,71)
ns<-matrix(NA_real_,10,6,dimnames=list(keys,periods));rs<-ns;s<-getcsv("actual-BEA-2025-03-27-vintage-GDP-expenditure-income-levels.csv");pdf<-file.path(a,"BEA-2024-GDP-third-estimate-2025-03-27.pdf")
if(file.exists(pdf)&&nzchar(Sys.which("pdftotext"))){
 tf<-tempfile(fileext=".txt");status<-system2("pdftotext",c("-layout",shQuote(pdf),shQuote(tf)));stopifnot(status==0);text<-readChar(tf,file.info(tf)$size,useBytes=TRUE);unlink(tf);pages<-strsplit(text,"\f",fixed=TRUE)[[1]]
 stopifnot(grepl("March 27, 2025",text,fixed=TRUE),grepl("Real GDP increased 2.8 percent in 2024",text,fixed=TRUE))
 for(i in seq_along(keys)){
  lines<-strsplit(pages[pg[i]],"\n",fixed=TRUE)[[1]];candidates<-lines[grepl(paste0("[[:space:]]",ln[i],"[[:space:]]*$"),lines)];values<-NULL
  for(line in candidates){v<-regmatches(line,gregexpr("-?[0-9][0-9,]*\\.[0-9]",line,perl=TRUE))[[1]];if(length(v)>=12){values<-as.numeric(gsub(",","",v,fixed=TRUE));break}}
  stopifnot(length(values)>=12);ns[i,]<-values[1:6];rs[i,]<-values[7:12]
 }
 for(i in seq_len(nrow(s))){stopifnot(ns[s$measure[i],s$period[i]]==as.numeric(s$current_billion_USD[i]),rs[s$measure[i],s$period[i]]==as.numeric(s$chained2017_billion_USD[i]));checks<-checks+2}
}else{for(i in seq_len(nrow(s))){ns[s$measure[i],s$period[i]]<-as.numeric(s$current_billion_USD[i]);rs[s$measure[i],s$period[i]]<-as.numeric(s$chained2017_billion_USD[i])};message("National-account fallback: public original-table selections")}
for(k in keys)for(t in periods){put(paste0("country_",k,"_",t,"_nominal"),ns[k,t]);put(paste0("country_",k,"_",t,"_chained"),rs[k,t])}
rec<-getcsv("derived-national-account-published-reconciliations.csv")
for(t in periods){
 n<-sum(ns[c("consumption","investment","government","exports"),t])-ns["imports",t];z<-sum(rs[c("consumption","investment","government","exports"),t])-rs["imports",t]
 values<-c(sum_current_C_I_G_X_minus_M=n,published_current_rounding_gap=ns["gdp",t]-n,GDP_minus_GDI_published_gap=ns["gdp",t]-ns["gdi",t],sum_chained_major_components=z,chained_nonadditivity_gap=rs["gdp",t]-z)
 row<-rec[rec$period==t,,drop=FALSE];for(k in names(values)){stopifnot(near(frac(row[[k]]),values[k]));checks<-checks+1;put(paste0("country_",t,"_",k),values[k])}
 gap<-ns["gdp",t]+ns["income_receipts_rest_world",t]-ns["income_payments_rest_world",t]-ns["gnp",t];stopifnot(abs(gap)<=.2+1e-10);checks<-checks+1;put(paste0("country_",t,"_GNP_published_rounding_gap"),gap)
}
ratio<-rs["gdp","2024Q4"]/rs["gdp","2024Q3"];growth<-c(2.8,2.4,100*(ratio-1),100*(ratio^4-1),100*(rs["gdp","2024Q4"]/rs["gdp","2023Q4"]-1));g<-getcsv("actual-and-derived-GDP-growth-period-distinctions.csv")
for(i in seq_along(growth)){stopifnot(near(frac(g$rate_percent[i]),growth[i]));checks<-checks+1;put(paste0("country_growth_",i-1,"_percent"),growth[i])}

sel<-getcsv("actual9876-ACS2024-Delaware-person-income-fields-missing-preserved.csv");zip<-file.path(a,"Census-ACS2024-1year-Delaware-person.zip");fields<-c("SERIALNO","SPORDER","STATE","AGEP","ADJINC","PWGTP","PINCP","WAGP")
if(file.exists(zip)){
 con<-unz(zip,"psam_p10.csv",open="r");records<-read.csv(con,colClasses="character",check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL);close(con);stopifnot(nrow(records)==9876,ncol(records)==286,identical(sel$source_row_id,as.character(seq_len(nrow(records)))))
 for(k in fields){stopifnot(identical(sel[[k]],records[[k]]));checks<-checks+nrow(records)}
}else{records<-sel;message("ACS fallback: public selected9876 records with unavailable values preserved")}
stopifnot(nrow(records)==nrow(sel));age<-as.numeric(records$AGEP);available<-nzchar(records$PINCP);adult<-age>=18;target<-adult&available;x<-as.numeric(records$PINCP[target])*as.numeric(records$ADJINC[target])/1e6;w<-as.numeric(records$PWGTP[target]);sw<-sum(w);num<-sum(w*x);wm<-num/sw;simple<-mean(x)
qvalue<-function(p){ord<-order(x,method="radix");x[ord][which(cumsum(w[ord])>=p*sw)[1]]}
summary<-c(source_rows=nrow(records),source_columns=286,source_person_weight_total=sum(as.numeric(records$PWGTP)),target_age_lower_bound=18,adult_rows=sum(adult),adult_available_income_rows=sum(target),adult_unavailable_income_rows=sum(adult&!available),adult_person_weight_total=sw,adult_negative_income_rows=sum(x<0),adult_zero_income_rows=sum(x==0),weighted_income_numerator_2024_USD=num,weighted_mean_personal_income_2024_USD=wm,unweighted_mean_personal_income_2024_USD=simple,lower_weighted_median_personal_income_2024_USD=qvalue(.5),actual_ADJINC=as.numeric(records$ADJINC[1]),adjustment_factor_exact=as.numeric(records$ADJINC[1])/1e6)
s<-getcsv("derived-ACS-adult-available-personal-income-summary.csv");for(k in names(summary)){stopifnot(near(frac(s[[k]]),summary[k]));checks<-checks+1;put(paste0("person_",k),summary[k])}
put("person_all_age_missing_PINCP",sum(!available));put("person_unique_source_household_person_keys",nrow(unique(records[c("SERIALNO","SPORDER")])));put("person_first_adjusted_income",as.numeric(records$PINCP[1])*as.numeric(records$ADJINC[1])/1e6);put("person_first_age",records$AGEP[1]);put("person_first_weight",records$PWGTP[1])
qs<-getcsv("derived-ACS-adult-weighted-income-quantiles.csv");for(i in seq_len(nrow(qs))){v<-qvalue(as.numeric(qs$percentile[i])/100);stopifnot(near(v,frac(qs$lower_weighted_quantile_2024_USD[i])));checks<-checks+1;put(paste0("person_quantile_",qs$percentile[i]),v)}
selectedBins<-list(x<0,x==0,x>0&x<25000,x>=25000&x<50000,x>=50000&x<100000,x>=100000);bs<-getcsv("derived-ACS-adult-signed-income-weighted-bins.csv")
for(i in seq_along(selectedBins)){keep<-selectedBins[[i]];n<-sum(keep);wt<-sum(w[keep]);stopifnot(n==as.numeric(bs$actual_source_rows[i]),wt==as.numeric(bs$person_weight_sum[i]),sw==as.numeric(bs$adult_available_person_weight_total[i]),near(wt/sw,frac(bs$weighted_fraction[i])));checks<-checks+4;put(paste0("person_bin_",i-1,"_source_rows"),n);put(paste0("person_bin_",i-1,"_weight"),wt);put(paste0("person_bin_",i-1,"_fraction"),wt/sw)}

s<-getcsv("actual-Costco-FY2024-and2023-quarter-versus-year-accounts.csv");html<-file.path(a,"Costco-FY2024-official-operating-results.html");periodCompany<-c("Q4_2024_16weeks_million_USD","Q4_2023_17weeks_million_USD","FY2024_52weeks_million_USD","FY2023_53weeks_million_USD");co<-matrix(NA_real_,nrow(s),4,dimnames=list(s$category,periodCompany))
if(file.exists(html)){
 text<-paste(readLines(html,warn=FALSE,encoding="UTF-8"),collapse="\n");tr<-regmatches(text,gregexpr("(?si)<tr[^>]*>.*?</tr>",text,perl=TRUE))[[1]]
 cells<-lapply(tr,function(line){td<-regmatches(line,gregexpr("(?si)<t[dh][^>]*>.*?</t[dh]>",line,perl=TRUE))[[1]];trimws(gsub("[[:space:]]+"," ",gsub("&nbsp;|&#160;"," ",gsub("<[^>]+>","",td))))})
 for(i in seq_len(nrow(s))){row<-Filter(function(x)length(x)&&identical(x[1],s$source_label[i]),cells)[[1]];v<-as.numeric(gsub(",","",row[grepl("^[0-9,]+$",row)],fixed=TRUE));stopifnot(length(v)==4);co[i,]<-v;for(k in periodCompany){stopifnot(co[i,k]==as.numeric(s[[k]][i]));checks<-checks+1}}
}else{for(k in periodCompany)co[,k]<-as.numeric(s[[k]]);message("Company fallback: public source-selected income-statement cells")}
for(k in s$category)for(t in periodCompany)put(paste0("company_",k,"_",t),co[k,t])
for(t in periodCompany){stopifnot(co["net_sales",t]+co["membership_fees",t]==co["total_revenue",t],co["total_revenue",t]-co["merchandise_costs",t]-co["sga",t]==co["operating_income",t]);checks<-checks+2;put(paste0("company_",t,"_operating_margin"),co["operating_income",t]/co["total_revenue",t])}
put("company_FY2024_weeks",52);put("company_FY2023_weeks",53);put("company_FY2024_weekly_revenue",co["total_revenue",periodCompany[3]]/52);put("company_FY2023_weekly_revenue",co["total_revenue",periodCompany[4]]/53)
h<-getcsv("hypothetical-three-stage-value-added-account.csv");for(i in seq_len(nrow(h))){output<-as.numeric(h$output_value[i]);input<-as.numeric(h$intermediate_input_value[i]);v<-output-input;stopifnot(v==as.numeric(h$value_added[i]));checks<-checks+1;put(paste0("hypothetical_stage_",i-1,"_output"),output);put(paste0("hypothetical_stage_",i-1,"_input"),input);put(paste0("hypothetical_stage_",i-1,"_VA"),v)}
put("hypothetical_gross_sales",sum(as.numeric(h$output_value)));put("hypothetical_value_added",sum(as.numeric(h$output_value)-as.numeric(h$intermediate_input_value)))
write.csv(data.frame(metric=names(m),value=sprintf("%.17g",m)),file.path(o,"econ13-r-results.csv"),row.names=FALSE,quote=TRUE)
cat("ECON13 base-R:",length(m),"metrics;",checks,"checks\n")
