%% Runs all RN estimation files - ROBUSTNESS: 2pp bins
%
% This script processes option prices into risk-neutral beliefs using
% 2 percentage point return state bins (robustness check)
%
% Uses the same underlying rnProbs.mat as the main specification;
% only the bin aggregation differs
%
% Execution flags (set to 1 to run each stage):
%   runbinary        - Stage 1: RN distributions -> Binary belief aggregation (resolving states)
%   runexport        - Stage 2: Binary beliefs -> CSV export for Stata
%   runbinaryallbins - Stage 3: RN distributions -> All-bin binary beliefs (for noise adjustment)
%
% Input data required:
%   Output/rnProbs.mat - RN probability distributions (from mat_01run_all_matlab)
%   Input/set_prices.mat, Input/zero_coupons.mat - Settlement and rate data
%
% Output:
%   Output/rnProbsBinary_2ppt.mat - Binary belief aggregates (resolving states, 2pp bins)
%   Output/rnProbsBinaryNoise_2ppt.mat - All-bin binary beliefs (for noise adjustment)
%   Output/binaryStata_2ppt.csv - Export for Stata analysis
%   ../Stata/Input/binaryStata_2ppt.csv - Same, in Stata input folder

% Preliminaries
clear;
close all;

% Set paths
script_folder = fileparts(which('mat_03run_all_matlab_2ppt.m'));
cd(script_folder);
addpath(genpath(script_folder));

% Execution flags
runbinary = 1;        % Set to 1 to aggregate into binary beliefs (resolving states, 2pp)
runexport = 1;        % Set to 1 to export CSV for Stata
runbinaryallbins = 1; % Set to 1 to create all-bin binary beliefs (for noise adjustment)

% Data parameters (set by mat_00master.m)
load('Input/params.mat', 'last_ex');

%% Convert to binary (2pp bins, resolving states)

if runbinary==1

    % Load data (reuses main spec rnProbs.mat)
    if ~exist('rnProb','var')
        load('Output/rnProbs.mat')
    end
    if ~exist('set_price','var') || ~exist('zc_rate','var')
        load Input/set_prices.mat;
        load Input/zero_coupons.mat;
    end
    zc_dates = date4;
    zc_dtm = dtm;

    % Run
    binary_probs_2ppt;

    % Save
    clear rnProb;
    save('Output/rnProbsBinary_2ppt.mat','-v7.3');

end

%% Calculate preliminary statistics and export to csv for estimation in Stata

if runexport==1

    % Load data
    if ~exist('binaryProbs','var')
        load Output/rnProbsBinary_2ppt.mat;
    end

    % Run
    binary_to_stata;

    % Export
    csvwrite('Output/binaryStata_2ppt.csv',exportMat);
    csvwrite('../Stata/Input/binaryStata_2ppt.csv',exportMat);
    disp('Exported binaryStata_2ppt.csv');

end

%% Convert RN distributions to all-bin binary beliefs (for noise adjustment in Stata)

if runbinaryallbins==1
    
    % Load data (reuses main spec rnProbs.mat)
    load('Output/rnProbs.mat')
    load Input/set_prices.mat;
    load Input/zero_coupons.mat;
    zc_dates = date4;
    zc_dtm = dtm;

    % Run all-bin binary processing (2pp bins)
    binary_probs_noise_2ppt;

    % Save
    save('Output/rnProbsBinaryNoise_2ppt.mat','-v7.3');

end
