Debug and improve adjust_for_splits() in the following code():

```
def ensure_series_types(df, price_col):
    df['date'] = pd.to_datetime(df['date'])
    df = df.sort_values('date').reset_index(drop=True)
    for col in ['volume', price_col]:
        df[col] = pd.to_numeric(df[col], errors='coerce')
    return df

def validate_raw_prices(df, price_col):
    invalid_price_mask = df[price_col] <= 0
    inconsistent_mask = pd.Series(False, index=df.index)
    if 'low' in df.columns and 'high' in df.columns:
        inconsistent_mask = (df['low'] > df['high'])

    local_error_mask = invalid_price_mask | inconsistent_mask
    df = df[~local_error_mask].copy()
    
    return df

def handle_stale_periods(df, price_col, max_stale_days=5):
    stale_groups = (df[price_col].diff() != 0).cumsum()
    
    period_lengths = df.groupby(stale_groups)[price_col].transform('size')
    long_stale_mask = period_lengths > max_stale_days
    
    is_intermediate_stale_row = (stale_groups.duplicated(keep='first') & 
                             stale_groups.duplicated(keep='last'))
    
    rows_to_drop_mask = long_stale_mask & is_intermediate_stale_row
    df = df[~rows_to_drop_mask].copy()
        
    return df

def adjust_for_splits(df, price_col, tolerance=0.05):
    split_ratios = {
        # Splits
        -0.50: 2,
        -0.666: 3,
        -0.75: 4,
        # Reverse Splits
        1.0: 0.5,
        2.0: 1/3,
        3.0: 1/4,
    }
    
    df['pct_change'] = df[price_col].pct_change()
    for pct, ratio in split_ratios.items():
        # Detect pct_changes that resemble splits
        is_potential_split = np.isclose(df['pct_change'], pct, atol=tolerance)
        if is_potential_split.any():
            print('split')
            split_indices = df.index[is_potential_split]
            for idx in split_indices:
                if idx == 0: continue
                
                # Check the next few days to ensure the price doesn't revert
                price_before = df.loc[idx - 1, price_col]
                price_at = df.loc[idx, price_col]
                
                if idx + 3 < len(df):
                    price_after = df.loc[idx + 1:idx + 3, price_col].median()
                    if not np.isclose(price_after, price_at, rtol=0.1):
                        continue
                
                # Adjust all prices before this date
                df.loc[:idx-1, price_col] = df.loc[:idx-1, price_col] / ratio

    df['pct_change'] = df[price_col].pct_change()
    return df

# Load historical series
latest = (datetime.now() - timedelta(days=365 * 6))
meta = []
file_list = os.listdir(data_path)
for file in tqdm(file_list, total=len(file_list)):
    if not file.endswith('.csv'):
        continue
    
    parts = os.path.splitext(file)[0].split('-')
    symbol, exchange, currency = parts[0], parts[1], parts[2]
    if not ((verified_df['symbol'] == symbol) & (verified_df['currency'] == currency)).any():
        continue
    
    # Load and clean raw series
    # try:
    df = load(data_path + file)
    df = ensure_series_types(df, price_col)
    df = validate_raw_prices(df, price_col)
    df = handle_stale_periods(df, price_col)
    df = adjust_for_splits(df, price_col)

    if df['date'].max() > latest:
        latest = df['date'].max()

    meta.append({
        'symbol': symbol,
        'currency': currency,
        'exchange_api': exchange,
        'df': df[['date', price_col, 'volume', 'pct_change']],
    })
    # except Exception as e:
    #     print(f"ERROR {file}: {e}")
        
meta = pd.DataFrame(meta)
copied = meta.copy()
copied['df'] = copied['df'].apply(lambda x: x.copy()) 
```

Why does it calculate price_before? And what is it doing exactly?