if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# ECON-03: base R actual atoms, exact-event CDFs and an explicit spread model.
args<-commandArgs(FALSE);filearg<-args[grepl("^--file=",args)]
if(length(filearg))setwd(dirname(normalizePath(sub("^--file=","",filearg[1]),winslash="/")))
workspace<-normalizePath("../..",winslash="/");common<-"\uc2e4\uc81c\ub370\uc774\ud130";data_dir<-"econ03-sources"
read_actual<-function(p)read.csv(p,fileEncoding="UTF-8-BOM",na.strings=c("","NA"),check.names=FALSE,stringsAsFactors=FALSE)
results<-numeric(0);add<-function(k,v){results[k]<<-as.numeric(v)}
near<-function(a,b,tol=1e-10)stopifnot(all(abs(a-b)<=tol*pmax(1,abs(a))))
fraction<-function(s){v<-strsplit(as.character(s),"/",fixed=TRUE)[[1]];as.numeric(v[1])/if(length(v)==2)as.numeric(v[2]) else 1}




# Numeric inputs are original actual source records; summaries are independently checked.
fraction<-function(s)vapply(as.character(s),function(v){if(is.na(v)||v=="")return(NA_real_);a<-strsplit(v,"/",fixed=TRUE)[[1]];as.numeric(a[1])/if(length(a)==2)as.numeric(a[2]) else 1},numeric(1),USE.NAMES=FALSE)
rawdir<-file.path(workspace,"work/textbooks-2026/raw");original<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-econ03/FRED-CPIAUCNS-table.html")
if(file.exists(original)){
 text<-paste(readLines(original,encoding="UTF-8",warn=FALSE),collapse=" ");for(s in c("CPIAUCNS","U.S. Bureau of Labor Statistics","Not Seasonally Adjusted","Monthly","Index 1982-1984=100","2026-10-14 8:08 AM CDT"))stopifnot(grepl(s,text,fixed=TRUE))
 pat<-'<th[^>]*>[0-9]{4}-[0-9]{2}-[0-9]{2}</th>\\s*<td[^>]*>\\s*[0-9]+(?:\\.[0-9]+)?\\s*</td>'
 nodes<-regmatches(text,gregexpr(pat,text,perl=TRUE))[[1]];dates<-sub('.*<th[^>]*>([0-9-]+)</th>.*',"\\1",nodes,perl=TRUE);vals<-as.numeric(sub('.*<td[^>]*>\\s*([0-9.]+)\\s*</td>.*',"\\1",nodes,perl=TRUE));stopifnot(length(nodes)==1000)
 nodes2<-regmatches(text,gregexpr('#[0-9]{4}-[0-9]{2}-[0-9]{2}\\|\\s*(?:[0-9]+(?:\\.[0-9]+)?|\\.)',text,perl=TRUE))[[1]];d2<-sub('^#([0-9-]+)\\|.*',"\\1",nodes2,perl=TRUE);v2<-sub('^#[0-9-]+\\|\\s*',"",nodes2,perl=TRUE);v2[v2=="."]<-NA_character_;dates<-c(dates,d2);vals<-c(vals,as.numeric(v2));stopifnot(length(nodes2)==365,length(dates)==1365,length(unique(dates))==1365,identical(as.Date(dates),seq(as.Date("1913-01-01"),as.Date("2026-09-01"),by="month")))
 keep<-dates>="1976-01-01"&dates<="2024-12-01";dates<-dates[keep];vals<-vals[keep]
}else{S<-read_actual(file.path(data_dir,"actual588-FRED-BLS-CPIAUCNS-monthly-levels1976-2024.csv"));dates<-S$date;vals<-S$actual_CPIAUCNS_index_source_decimal}
add("country_original_visible_rows",1000);add("country_original_continuation_rows",365);add("country_original_unique_months",1365);stopifnot(length(vals)==588,all(!is.na(vals)));S<-read_actual(file.path(data_dir,"actual588-FRED-BLS-CPIAUCNS-monthly-levels1976-2024.csv"));stopifnot(nrow(S)==588,all(S$date==dates),all(S$series_id=="CPIAUCNS"),all(S$unit=="1982-1984=100"),all(S$adjustment=="not_seasonally_adjusted"),all(S$frequency=="monthly"));near(S$actual_CPIAUCNS_index_source_decimal,vals);near(S$year,as.integer(substr(dates,1,4)));near(S$month,as.integer(substr(dates,6,7)))
years<-1976:2024;annual<-vapply(years,function(y)mean(vals[substr(dates,1,4)==as.character(y)]),numeric(1));names(annual)<-years;base<-unname(annual["1976"]);last<-unname(annual["2024"]);A<-read_actual(file.path(data_dir,"derived49-annual-arithmetic-means-of-published-monthly-CPI.csv"));B<-read_actual(file.path(data_dir,"derived49-CPI-rebasings-2024-equals100.csv"));stopifnot(nrow(A)==49,nrow(B)==49,all(A$is_independently_reported_BLS_annual_statistic=="False"),all(A$monthly_display_rounding_retained=="True"),all(B$rebasing_changes_price_ratios=="False"));near(A$year,years);near(A$monthly_records,rep(12,49));near(fraction(A$arithmetic_mean_of_published_monthly_levels_exact),annual);near(A$arithmetic_mean_of_published_monthly_levels_Decimal80_approx,annual);near(B$year,years);near(fraction(B$derived_annual_mean_of_published_CPI_months_exact),annual);near(fraction(B$chosen_rebased2024_equals100_exact),annual/last*100)
for(i in seq_along(years)){v<-c(annualMean=annual[i],rebased2024Equals100=annual[i]/last*100,ratioTo1976=annual[i]/base);names(v)<-c("annualMean","rebased2024Equals100","ratioTo1976");for(k in names(v))add(paste0("country_",years[i],"_",k),unname(v[k]))};add("country_selected_months",588);add("country_selected_years",49);add("country_reference1982to1984_mean_of_rounded_months",mean(vals[substr(dates,1,4)>="1982"&substr(dates,1,4)<="1984"]));add("country_2024_annual_mean_growth",unname(annual["2024"]/annual["2023"]-1))
archive<-file.path(rawdir,"proximity.zip");P<-read_actual(file.path(data_dir,"actual3613-historical-raw-log-wages-and-explicit-CPI-unit-conversions.csv"));if(file.exists(archive)){con<-unz(archive,"nls.dat");lines<-readLines(con,warn=FALSE);close(con);part<-function(a,b){x<-trimws(substr(lines,a,b));x[x=="."]<-NA_character_;as.numeric(x)};code<-part(1,5);wage<-part(128,132);logs<-part(86,97)}else{code<-P$original_person_code;wage<-P$actual_raw1976_hourly_wage_cents;logs<-P$actual_source_trimmed_log1976_cents_per_hour};stopifnot(length(wage)==3613,nrow(P)==3613,code[1]==2,wage[1]==548);near(P$source_row_id,seq_len(3613));near(P$original_person_code,code)
for(pair in list(c("actual_raw1976_hourly_wage_cents","wage"),c("actual_source_trimmed_log1976_cents_per_hour","logs"))){o<-get(pair[2]);s<-fraction(P[[pair[1]]]);stopifnot(identical(is.na(o),is.na(s)));near(o[!is.na(o)],s[!is.na(s)])};ok<-!is.na(wage);near(fraction(P$actual_raw1976_hourly_wage_USD_exact[ok]),wage[ok]/100);near(fraction(P$derived_same_record_in2024_CPI_purchasing_power_USD_per_hour_exact[ok]),wage[ok]/100*last/base);stopifnot(all(P$raw_wage_available==ifelse(ok,"True","False")),all(P$source_trimmed_log_available==ifelse(!is.na(logs),"True","False")),all(P$is_actual2024_wage_observation=="False"),all(P$is_person_specific_cost_of_living_index=="False"));w<-wage[1]/100
S<-read_actual(file.path(data_dir,"derived49-price-unit-conversions-of-one-actual1976-wage.csv"));stopifnot(nrow(S)==49,all(S$actual1976_source_row==1),all(S$actual1976_original_person_code==2),all(S$actual1976_raw_hourly_wage_cents==548),all(S$reference_year_wage_was_observed==ifelse(years==1976,"True","False")),all(S$individual_cost_of_living_estimated=="False"));near(S$reference_price_year,years);near(fraction(S$derived_purchasing_power_unit_USD_per_hour_exact),w*annual/base);near(fraction(S$reference_CPI_annual_mean_of_published_months_exact),annual);near(fraction(S$base1976_CPI_annual_mean_of_published_months_exact),rep(base,49));for(i in seq_along(years))add(paste0("person_priceYear",years[i],"_chosenCPIUnitWage"),w*annual[i]/base)
v<-c(records=length(wage),rawAvailable=sum(!is.na(wage)),rawUnavailable=sum(is.na(wage)),trimmedLogsAvailable=sum(!is.na(logs)),trimmedLogsUnavailable=sum(is.na(logs)),rawAvailableLogUnavailable=sum(!is.na(wage)&is.na(logs)),firstRawCents=wage[1],first1976USD=w,chosen2024CPIUnitUSD=w*last/base);for(k in names(v))add(paste0("person_",k),v[[k]])
apple<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html");categories<-c("iPhone","Mac","iPad","Wearables, Home and Accessories","Services");sales<-read_actual(file.path(data_dir,"actual-ten-Apple-category-fiscal-year-nominal-sales.csv"));values<-list();clean<-function(s){s<-gsub("<[^>]+>"," ",s);s<-gsub("&nbsp;|&#160;"," ",s);s<-gsub("&amp;","&",s,fixed=FALSE);trimws(gsub("[[:space:]]+"," ",s))};label<-function(s)sub("\\s*\\([0-9]+\\)\\s*$","",s,perl=TRUE)
if(file.exists(apple)){
 text<-paste(readLines(apple,encoding="UTF-8",warn=FALSE),collapse=" ");plain<-clean(text);stopifnot(grepl("2024 and 2022 spanned 52 weeks each",plain,fixed=TRUE),grepl("2023 spanned 53 weeks",plain,fixed=TRUE));ts<-regmatches(text,gregexpr("(?is)<table\\b[^>]*>.*?</table>",text,perl=TRUE))[[1]];tables<-list()
 for(tab in ts){rs<-regmatches(tab,gregexpr("(?is)<tr\\b[^>]*>.*?</tr>",tab,perl=TRUE))[[1]];rows<-lapply(rs,function(r){cs<-regmatches(r,gregexpr("(?is)<t[dh]\\b[^>]*>.*?</t[dh]>",r,perl=TRUE))[[1]];vapply(cs,clean,character(1))});rows<-Filter(function(r)length(r)>0,rows);labels<-vapply(rows,function(r)label(r[1]),character(1));if(all(c(categories,"Total net sales")%in%labels))tables[[length(tables)+1]]<-rows};stopifnot(length(tables)>0)
 for(name in c(categories,"Total net sales")){hits<-list();for(table in tables)for(row in table)if(label(row[1])==name){v<-row[-1];v<-v[grepl("^[0-9][0-9,]*$",v)];if(length(v)==3)hits[[length(hits)+1]]<-as.numeric(gsub(",","",v,fixed=TRUE))};stopifnot(length(hits)>0);for(v in hits)near(v,hits[[1]]);values[[name]]<-hits[[1]]}
}else{for(name in categories)values[[name]]<-vapply(c(2024,2023),function(y)sales$actual_nominal_net_sales_million_USD[sales$fiscal_year==y&sales$actual_category==name],numeric(1));values[["Total net sales"]]<-c(sum(vapply(values,function(v)v[1],numeric(1))),sum(vapply(values,function(v)v[2],numeric(1))))}
prior<-values[["Total net sales"]][2];current<-values[["Total net sales"]][1];stopifnot(prior==383285,current==391035,nrow(sales)==10,all(sales$is_physical_quantity=="False"),all(sales$common_product_price_identified=="False"));index<-0;for(y in c(2023,2024)){pos<-if(y==2023)2 else 1;weeks<-if(y==2023)53 else 52;for(name in categories){index<-index+1;stopifnot(sales$actual_category[index]==name);near(sales$fiscal_year[index],y);near(sales$fiscal_weeks[index],weeks);near(sales$actual_nominal_net_sales_million_USD[index],values[[name]][pos])}}
S<-read_actual(file.path(data_dir,"derived-five-actual-category-nominal-growth-contributions.csv"));stopifnot(nrow(S)==5,all(S$actual_category==categories),all(S$is_price_or_volume_causal_effect=="False"));rates<-numeric(5);contrib<-numeric(5)
for(i in seq_along(categories)){name<-categories[i];old<-values[[name]][2];new<-values[[name]][1];rate<-new/old-1;weight<-old/prior;contribution<-weight*rate;rates[i]<-rate;contrib[i]<-contribution;v<-c(FY2023Sales=old,FY2024Sales=new,difference=new-old,nominalGrowth=rate,priorRevenueWeight=weight,growthContribution=contribution);keys<-c("actual_FY2023_sales_million_USD","actual_FY2024_sales_million_USD","observed_nominal_difference_million_USD_exact","observed_category_nominal_growth_fraction_exact","FY2023_nominal_sales_weight_exact","nominal_total_growth_contribution_fraction_exact");for(j in seq_along(v)){near(fraction(S[[keys[j]]][i]),v[j]);add(paste0("company_category",i-1,"_",names(v)[j]),unname(v[j]))}}
g<-current/prior-1;unweighted<-mean(rates);pw<-prior/53;nw<-current/52;wg<-nw/pw-1;near(sum(contrib),g);S<-read_actual(file.path(data_dir,"actual-annual-totals-and-mechanical-week-normalization.csv"));stopifnot(nrow(S)==1,S$weekly_path_is_observed=="False",S$calendar_CPI_is_identified_Apple_output_deflator=="False",S$physical_quantity_growth_identified=="False");v<-c(FY2023Total=prior,FY2024Total=current,FY2023Weeks=53,FY2024Weeks=52,annualNominalGrowth=g,unweightedCategoryGrowth=unweighted,FY2023MechanicalPerWeek=pw,FY2024MechanicalPerWeek=nw,mechanicalPerWeekGrowth=wg);keys<-c("actual_FY2023_total_million_USD","actual_FY2024_total_million_USD","actual_FY2023_weeks","actual_FY2024_weeks","observed_nominal_annual_growth_fraction_exact","unweighted_mean_of_five_category_growths_exact","mechanical_FY2023_mean_revenue_per_week_million_USD_exact","mechanical_FY2024_mean_revenue_per_week_million_USD_exact","mechanical_per_week_mean_growth_fraction_exact");for(i in seq_along(v)){near(fraction(S[[keys[i]]]),v[i]);add(paste0("company_",names(v)[i]),unname(v[i]))}
write.csv(data.frame(metric=names(results),value=unname(results)),"econ03-r-results.csv",row.names=FALSE);cat("ECON-03:",length(results),"actual-source and explicitly selected price-unit metrics independently checked.\n")
