#!/bin/bash

set -e

echo "Chemaxon Java API migration script for version 26.x"
echo ""

usage() {
    echo "Usage: $0 <directory>"
    echo ""
    echo "Migrates Java class references in all .java files within the specified directory."
    exit 1
}

if [ $# -ne 1 ]; then
    echo "Error: Invalid number of arguments"
    usage
fi

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' does not exist"
    exit 1
fi

# Class mappings
# Format: old.package.OldClass new.package.NewClass
MAPPINGS="
chemaxon.calculations.ElementalAnalyser chemaxon.core.calculations.ElementalAnalyzer
chemaxon.calculations.Ring chemaxon.core.calculations.Ring
chemaxon.calculations.TopologyAnalyser chemaxon.core.calculations.TopologyAnalyzer
chemaxon.calculations.cip.CIPStereoCalculator chemaxon.core.calculations.stereo.CIPStereoCalculator
chemaxon.calculations.clean.AtomChangeEventListener chemaxon.core.calculations.clean.Cleaner.AtomChangeEventListener
chemaxon.calculations.clean.Cleaner chemaxon.core.calculations.clean.Cleaner
chemaxon.calculations.hydrogenize.Hydrogenize chemaxon.core.calculations.Hydrogenizer
chemaxon.calculations.nmr.Multiplet chemaxon.calculations.nmr.NMRMultiplet
chemaxon.calculations.nmr.NMRCoefficient.ErrorClassification chemaxon.calculations.nmr.NMRErrorClassification
chemaxon.calculations.nmr.io.NMRExporter chemaxon.calculations.nmr.NMRExporter
chemaxon.calculations.pka.PKaTrainingResult chemaxon.calculations.PkaTrainingResult
chemaxon.calculations.pka.PKaTrainingResult.PKaType chemaxon.calculations.PkaTrainingResult.PkaType
chemaxon.calculations.stereo.Stereochemistry chemaxon.core.calculations.stereo.Stereochemistry
chemaxon.calculator.Calculator chemaxon.calculations.api.Calculator
chemaxon.calculator.CalculatorBuilder chemaxon.calculations.api.CalculatorBuilder
chemaxon.calculator.CalculatorError chemaxon.calculations.api.CalculatorError
chemaxon.calculator.CalculatorFormatter chemaxon.calculations.api.CalculatorFormatter
chemaxon.calculator.CalculatorInputChecker chemaxon.calculations.api.CalculatorInputChecker
chemaxon.calculator.CalculatorLogger chemaxon.calculations.api.CalculatorLogger
chemaxon.calculator.CalculatorTag chemaxon.calculations.api.CalculatorTag
chemaxon.calculator.HeavyAtomLimitChecker chemaxon.calculations.api.HeavyAtomLimitChecker
chemaxon.calculator.ProgressableCalculator chemaxon.calculations.api.ProgressableCalculator
chemaxon.calculator.TaggedCalculator chemaxon.calculations.api.TaggedCalculator
chemaxon.calculator.TaggedCalculatorInputChecker chemaxon.calculations.api.TaggedCalculatorInputChecker
chemaxon.checkers.DoubleBondStereoErrorChecker chemaxon.checkers.DoubleBondStereoErrorChecker
chemaxon.checkers.Persistent chemaxon.checkers.PersistentProperty
chemaxon.checkers.logger.StructureCheckerLogger chemaxon.structurechecker.StructureCheckerMonitor
chemaxon.checkers.result.ConvertConstants chemaxon.checkers.result.ConversionConstants
chemaxon.checkers.runner.AdvancedCheckerRunner chemaxon.structurechecker.AdvancedCheckerRunner
chemaxon.checkers.runner.BasicCheckerRunner chemaxon.structurechecker.BasicCheckerRunner
chemaxon.checkers.runner.CheckerRunner chemaxon.structurechecker.CheckerRunner
chemaxon.checkers.runner.configuration.reader.ActionStringBasedConfigurationReader chemaxon.structurechecker.configuration.StructureCheckerActionStringReader
chemaxon.checkers.runner.configuration.reader.ConfigurationReader chemaxon.structurechecker.configuration.StructureCheckerConfigurationReader
chemaxon.checkers.runner.configuration.reader.XMLBasedConfigurationReader chemaxon.structurechecker.configuration.StructureCheckerConfigurationXmlReader
chemaxon.checkers.runner.configuration.writer.ActionStringBasedConfigurationWriter chemaxon.structurechecker.configuration.StructureCheckerActionStringWriter
chemaxon.checkers.runner.configuration.writer.ConfigurationWriter chemaxon.structurechecker.configuration.StructureCheckerConfigurationWriter
chemaxon.checkers.runner.configuration.writer.XMLBasedConfigurationWriter chemaxon.structurechecker.configuration.StructureCheckerConfigurationXmlWriter
chemaxon.checkers.util.AtomLabels chemaxon.checkers.AtomLabels
chemaxon.checkers.util.DataExclusionList chemaxon.checkers.AttachedDataChecker.DataExclusionList
chemaxon.clustering.JarvisPatrick chemaxon.clustering.JarvisPatrickClustering
chemaxon.clustering.NearestNeighbors chemaxon.clustering.NearestNeighborsClustering
chemaxon.clustering.libmcs.adapter.LegacyLibraryMcsAdapter chemaxon.clustering.libmcs.LegacyLibraryMcsAdapter
chemaxon.clustering.libmcs.adapter.LegacyLibraryMcsParameters chemaxon.clustering.libmcs.LegacyLibraryMcsParameters
chemaxon.common.util.MProgressMonitor chemaxon.core.util.MProgressMonitor
chemaxon.core.ChemConst chemaxon.struc.PeriodicTable
chemaxon.core.calculations.valencecheck.ValenceCheckOptions chemaxon.struc.ValenceCheckOptions
chemaxon.core.util.BondTable chemaxon.struc.BondTable
chemaxon.descriptors.GenerateMD chemaxon.jchem.descriptors.GenerateMD
chemaxon.descriptors.MDArrayReader chemaxon.jchem.descriptors.MDArrayReader
chemaxon.descriptors.MDDBReader chemaxon.jchem.descriptors.MDDBReader
chemaxon.descriptors.MDDBWriter chemaxon.jchem.descriptors.MDDBWriter
chemaxon.descriptors.MDFileReader chemaxon.jchem.descriptors.MDFileReader
chemaxon.descriptors.MDFileWriter chemaxon.jchem.descriptors.MDFileWriter
chemaxon.descriptors.MDHitEvaluator chemaxon.jchem.descriptors.MDHitEvaluator
chemaxon.descriptors.MDHypothesisCreator chemaxon.jchem.descriptors.MDHypothesisCreator
chemaxon.descriptors.MDHypothesisGenerator chemaxon.jchem.descriptors.MDHypothesisGenerator
chemaxon.descriptors.MDMetricOptimizer chemaxon.jchem.descriptors.MDMetricOptimizer
chemaxon.descriptors.MDReader chemaxon.jchem.descriptors.MDReader
chemaxon.descriptors.MDReaderException chemaxon.jchem.descriptors.MDReaderException
chemaxon.descriptors.MDSet chemaxon.jchem.descriptors.MDSet
chemaxon.descriptors.MDSetParameters chemaxon.jchem.descriptors.MDSetParameters
chemaxon.descriptors.MDSimilarity chemaxon.jchem.descriptors.MDSimilarity
chemaxon.descriptors.MDSimilarityResultWriter chemaxon.jchem.descriptors.MDSimilarityResultWriter
chemaxon.descriptors.MDWriter chemaxon.jchem.descriptors.MDWriter
chemaxon.descriptors.MDWriterException chemaxon.jchem.descriptors.MDWriterException
chemaxon.formats.MolConverter chemaxon.formats.converter.MolConverter
chemaxon.formats.documents.jchemexcel.ILocation chemaxon.office.jchemexcel.ILocation
chemaxon.formats.documents.jchemexcel.IMoleculeMap chemaxon.office.jchemexcel.IMoleculeMap
chemaxon.formats.documents.jchemexcel.IWorkbookReader chemaxon.office.jchemexcel.IWorkbookReader
chemaxon.formats.documents.jchemexcel.JChemExcelAPI chemaxon.office.jchemexcel.JChemExcelAPI
chemaxon.formats.documents.jchemexcel.StructureToJC4XL chemaxon.office.jchemexcel.StructureToJC4XL
chemaxon.formats.documents.jchemexcel.WorkbookHandlerFactory chemaxon.office.jchemexcel.WorkbookHandlerFactory
chemaxon.formats.documents.jchemoffice.BatchProcessingException chemaxon.office.jchemoffice.BatchProcessingException
chemaxon.formats.documents.jchemoffice.CardLayoutArrangement chemaxon.office.jchemoffice.CardLayoutArrangement
chemaxon.formats.documents.jchemoffice.CodeGenerator chemaxon.office.jchemoffice.CodeGenerator
chemaxon.formats.documents.jchemoffice.ConditionalRuleOperators chemaxon.office.jchemoffice.ConditionalRuleOperators
chemaxon.formats.documents.jchemoffice.ConditionRule chemaxon.office.jchemoffice.ConditionRule
chemaxon.formats.documents.jchemoffice.ConversionOptions chemaxon.office.jchemoffice.ConversionOptions
chemaxon.formats.documents.jchemoffice.DataType chemaxon.office.jchemoffice.DataType
chemaxon.formats.documents.jchemoffice.DocumentHandlerFactory chemaxon.office.jchemoffice.DocumentHandlerFactory
chemaxon.formats.documents.jchemoffice.DocumentType chemaxon.office.jchemoffice.DocumentType
chemaxon.formats.documents.jchemoffice.DocumentUtility chemaxon.office.jchemoffice.DocumentUtility
chemaxon.formats.documents.jchemoffice.FileNameGenerationMode chemaxon.office.jchemoffice.FileNameGenerationMode
chemaxon.formats.documents.jchemoffice.FontAlignment chemaxon.office.jchemoffice.FontAlignment
chemaxon.formats.documents.jchemoffice.FontStyle chemaxon.office.jchemoffice.FontStyle
chemaxon.formats.documents.jchemoffice.GenericOptions chemaxon.office.jchemoffice.GenericOptions
chemaxon.formats.documents.jchemoffice.ICardLayout chemaxon.office.jchemoffice.ICardLayout
chemaxon.formats.documents.jchemoffice.ICellData chemaxon.office.jchemoffice.ICellData
chemaxon.formats.documents.jchemoffice.ICellFormat chemaxon.office.jchemoffice.ICellFormat
chemaxon.formats.documents.jchemoffice.ICodeGenerator chemaxon.office.jchemoffice.ICodeGenerator
chemaxon.formats.documents.jchemoffice.IConversionOptions chemaxon.office.jchemoffice.IConversionOptions
chemaxon.formats.documents.jchemoffice.IDocumentConverter chemaxon.office.jchemoffice.IDocumentConverter
chemaxon.formats.documents.jchemoffice.IDocumentReader chemaxon.office.jchemoffice.IDocumentReader
chemaxon.formats.documents.jchemoffice.IDocumentTemplateWriter chemaxon.office.jchemoffice.IDocumentTemplateWriter
chemaxon.formats.documents.jchemoffice.IDocumentWriter chemaxon.office.jchemoffice.IDocumentWriter
chemaxon.formats.documents.jchemoffice.IGenericOptions chemaxon.office.jchemoffice.IGenericOptions
chemaxon.formats.documents.jchemoffice.ImageGenerationType chemaxon.office.jchemoffice.ImageGenerationType
chemaxon.formats.documents.jchemoffice.IMoleculeData chemaxon.office.jchemoffice.IMoleculeData
chemaxon.formats.documents.jchemoffice.IMoleculeRenderer chemaxon.office.jchemoffice.IMoleculeRenderer
chemaxon.formats.documents.jchemoffice.IPropertyTableCellFormats chemaxon.office.jchemoffice.IPropertyTableCellFormats
chemaxon.formats.documents.jchemoffice.ISettings chemaxon.office.jchemoffice.ISettings
chemaxon.formats.documents.jchemoffice.ITableCell chemaxon.office.jchemoffice.ITableCell
chemaxon.formats.documents.jchemoffice.ITableModel chemaxon.office.jchemoffice.ITableModel
chemaxon.formats.documents.jchemoffice.ITemplateWriterOptions chemaxon.office.jchemoffice.ITemplateWriterOptions
chemaxon.formats.documents.jchemoffice.Location chemaxon.office.jchemoffice.Location
chemaxon.formats.documents.jchemoffice.MoleculeData chemaxon.office.jchemoffice.MoleculeData
chemaxon.formats.documents.jchemoffice.MoleculeMap chemaxon.office.jchemoffice.MoleculeMap
chemaxon.formats.documents.jchemoffice.MoleculeRenderContainer chemaxon.office.jchemoffice.MoleculeRenderContainer
chemaxon.formats.documents.jchemoffice.PropertyColoring chemaxon.office.jchemoffice.PropertyColoring
chemaxon.formats.documents.jchemoffice.PropertyTablePosition chemaxon.office.jchemoffice.PropertyTablePosition
chemaxon.formats.documents.jchemoffice.ReportSettings chemaxon.office.jchemoffice.ReportSettings
chemaxon.formats.documents.jchemoffice.SupportedOLETypes chemaxon.office.jchemoffice.SupportedOLETypes
chemaxon.formats.documents.jchemoffice.TemplateWriterOptions chemaxon.office.jchemoffice.TemplateWriterOptions
chemaxon.formats.recognizer.Recognizer chemaxon.formats.Recognizer
chemaxon.jchem.db.DatabaseConstants chemaxon.jchem.db.constants.DatabaseConstants
chemaxon.jchem.db.DatabaseSearchException chemaxon.jchem.db.exceptions.JChemSearchException
chemaxon.jchem.db.Exporter chemaxon.jchem.db.TableExporter
chemaxon.jchem.db.Importer chemaxon.jchem.db.TableImporter
chemaxon.jchem.db.MDTableHandler chemaxon.jchem.descriptors.MDTableHandler
chemaxon.jchem.db.RecalculationException chemaxon.jchem.db.exceptions.RecalculationException
chemaxon.jchem.db.RegenerationConstants chemaxon.jchem.db.constants.RegenerationConstants
chemaxon.jchem.db.StructureTableOptions chemaxon.jchem.db.TableOptions
chemaxon.jchem.db.TableTypeConstants chemaxon.jchem.db.constants.TableTypeConstants
chemaxon.jchem.db.Transfer chemaxon.jchem.db.constants.TableTransferConstants
chemaxon.jchem.db.TransferException chemaxon.jchem.db.exceptions.TableTransferException
chemaxon.jchem.db.Updater chemaxon.jchem.db.DatabaseUpdater
chemaxon.jchem.db.UpdateHandler chemaxon.jchem.db.TableUpdateHandler
chemaxon.jchem.db.UpdateHandlerException chemaxon.jchem.db.exceptions.TableUpdateHandlerException
chemaxon.jchem.file.ProgressWriter chemaxon.jchem.db.ProgressWriter
chemaxon.jep.ChemContext chemaxon.chemterms.ChemTermsContext
chemaxon.jep.ChemJEP chemaxon.chemterms.ChemTermsExpression
chemaxon.jep.ConstantTable chemaxon.chemterms.ConstantTable
chemaxon.jep.ConstantTableBuilder chemaxon.chemterms.ConstantTableBuilder
chemaxon.jep.CustomFunction chemaxon.chemterms.CustomFunction
chemaxon.jep.Evaluator chemaxon.chemterms.ChemTermsEvaluator
chemaxon.jep.FingerprintGenerator chemaxon.chemterms.FingerprintGenerator
chemaxon.jep.JepException chemaxon.chemterms.ChemTermsException
chemaxon.jep.context.AtomContext chemaxon.chemterms.AtomContext
chemaxon.jep.context.MolContext chemaxon.chemterms.MolContext
chemaxon.jep.context.ReactionContext chemaxon.chemterms.ReactionContext
chemaxon.jep.context.SearchContext chemaxon.chemterms.SearchContext
chemaxon.license.Licensable chemaxon.license.api.Licensable
chemaxon.license.LicenseException chemaxon.license.api.LicenseException
chemaxon.marvin.MolPrinter chemaxon.marvin.beans.MolPrinter
chemaxon.marvin.alignment.Alignment chemaxon.alignment.Alignment
chemaxon.marvin.alignment.AlignmentAccuracyMode chemaxon.alignment.AlignmentAccuracyMode
chemaxon.marvin.alignment.AlignmentBase chemaxon.alignment.AlignmentBase
chemaxon.marvin.alignment.AlignmentException chemaxon.alignment.AlignmentException
chemaxon.marvin.alignment.AlignmentMolecule chemaxon.alignment.AlignmentMolecule
chemaxon.marvin.alignment.AlignmentMoleculeFactory chemaxon.alignment.AlignmentMoleculeFactory
chemaxon.marvin.alignment.AlignmentProperties chemaxon.alignment.AlignmentProperties
chemaxon.marvin.alignment.AlignmentResult chemaxon.alignment.AlignmentResult
chemaxon.marvin.alignment.AlignOnPairedAtoms chemaxon.alignment.AlignOnPairedAtoms
chemaxon.marvin.alignment.AlignRigidEasy chemaxon.alignment.AlignRigidEasy
chemaxon.marvin.alignment.AtropIsomerDetector chemaxon.alignment.AtropIsomerDetector
chemaxon.marvin.alignment.DihedralRotator chemaxon.alignment.DihedralRotator
chemaxon.marvin.alignment.MCSAlignment chemaxon.alignment.MCSAlignment
chemaxon.marvin.alignment.MCSAlignmentResult chemaxon.alignment.MCSAlignmentResult
chemaxon.marvin.alignment.MinMaxDistance chemaxon.alignment.MinMaxDistance
chemaxon.marvin.alignment.MMPAlignment chemaxon.alignment.MMPAlignment
chemaxon.marvin.alignment.MMPAlignmentProperties chemaxon.alignment.MMPAlignmentProperties
chemaxon.marvin.alignment.MMPAlignmentResult chemaxon.alignment.MMPAlignmentResult
chemaxon.marvin.alignment.MolAligner chemaxon.alignment.MolAligner
chemaxon.marvin.alignment.NodeColor chemaxon.alignment.NodeColor
chemaxon.marvin.alignment.PairwiseAlignment chemaxon.alignment.PairwiseAlignment
chemaxon.marvin.alignment.PairwiseComparison chemaxon.alignment.PairwiseComparison
chemaxon.marvin.alignment.PairwiseSimilarity3D chemaxon.alignment.PairwiseSimilarity3D
chemaxon.marvin.alignment.Pharmacophore3D chemaxon.alignment.Pharmacophore3D
chemaxon.marvin.alignment.RotatableBondDetector chemaxon.alignment.RotatableBondDetector
chemaxon.marvin.alignment.ShapeData chemaxon.alignment.ShapeData
chemaxon.marvin.alignment.atrop.BondInfo chemaxon.alignment.DihedralScanResult.BondInfo
chemaxon.marvin.alignment.atrop.DihedralScanResult chemaxon.alignment.DihedralScanResult
chemaxon.marvin.alignment.atrop.DihedralScanStep chemaxon.alignment.DihedralScanResult.ScanStep
chemaxon.marvin.beans.MarvinPaneBeanInfo chemaxon.marvin.beans.MarvinPaneBeanInfo
chemaxon.marvin.beans.MSketchPaneBeanInfo chemaxon.marvin.beans.MSketchPaneBeanInfo
chemaxon.marvin.beans.MViewEditor chemaxon.marvin.beans.MViewCellEditor
chemaxon.marvin.beans.MViewPaneBeanInfo chemaxon.marvin.beans.MViewPaneBeanInfo
chemaxon.marvin.beans.MViewRenderer chemaxon.marvin.beans.MViewCellRenderer
chemaxon.marvin.calculations.AlignmentPlugin chemaxon.calculations.AlignmentPlugin
chemaxon.marvin.calculations.ChargePlugin chemaxon.calculations.ChargePlugin
chemaxon.marvin.calculations.ConformerPlugin chemaxon.calculations.ConformerPlugin
chemaxon.marvin.calculations.ElementalAnalyserPlugin chemaxon.calculations.ElementalAnalysisPlugin
chemaxon.marvin.calculations.GeometryPlugin chemaxon.calculations.GeometryPlugin
chemaxon.marvin.calculations.HBDAPlugin chemaxon.calculations.HBDAPlugin
chemaxon.marvin.calculations.HergPlugin chemaxon.calculations.admet.HergPlugin
chemaxon.marvin.calculations.HlbPlugin chemaxon.calculations.HLBPlugin
chemaxon.marvin.calculations.HuckelAnalysisPlugin chemaxon.calculations.HuckelAnalysisPlugin
chemaxon.marvin.calculations.IonChargePlugin chemaxon.calculations.IonChargePlugin
chemaxon.marvin.calculations.IsoelectricPointPlugin chemaxon.calculations.IsoelectricPointPlugin
chemaxon.marvin.calculations.IUPACNamingPlugin chemaxon.calculations.ChemicalNamePlugin
chemaxon.marvin.calculations.logDPlugin chemaxon.calculations.LogDPlugin
chemaxon.marvin.calculations.logPPlugin chemaxon.calculations.LogPPlugin
chemaxon.marvin.calculations.LogPMethod chemaxon.calculations.LogPMethod
chemaxon.marvin.calculations.MajorMicrospeciesAccessorPlugin chemaxon.calculations.MajorMicrospeciesAccessorPlugin
chemaxon.marvin.calculations.MajorMicrospeciesPlugin chemaxon.calculations.MajorMicrospeciesPlugin
chemaxon.marvin.calculations.MarkushEnumerationPlugin chemaxon.calculations.MarkushEnumerationPlugin
chemaxon.marvin.calculations.MolecularDynamicsPlugin chemaxon.calculations.MolecularDynamicsPlugin
chemaxon.marvin.calculations.MSAPlugin chemaxon.calculations.MSAPlugin
chemaxon.marvin.calculations.OrbitalElectronegativityPlugin chemaxon.calculations.OrbitalElectronegativityPlugin
chemaxon.marvin.calculations.PkaPlugin chemaxon.calculations.PkaPlugin
chemaxon.marvin.calculations.pKaPlugin chemaxon.calculations.PkaPlugin
chemaxon.marvin.calculations.PolarizabilityPlugin chemaxon.calculations.PolarizabilityPlugin
chemaxon.marvin.calculations.RefractivityPlugin chemaxon.calculations.RefractivityPlugin
chemaxon.marvin.calculations.ResonancePlugin chemaxon.calculations.ResonancePlugin
chemaxon.marvin.calculations.StereoisomerPlugin chemaxon.calculations.StereoisomerPlugin
chemaxon.marvin.calculations.StructuralFrameworksPlugin chemaxon.calculations.StructuralFrameworksPlugin
chemaxon.marvin.calculations.TautomerizationPlugin chemaxon.calculations.TautomerPlugin
chemaxon.marvin.calculations.TopologyAnalyserPlugin chemaxon.calculations.TopologyAnalysisPlugin
chemaxon.marvin.calculations.TPSAPlugin chemaxon.calculations.TPSAPlugin
chemaxon.marvin.io.Encoding chemaxon.formats.Encoding
chemaxon.marvin.io.MDocSource chemaxon.formats.MDocSource
chemaxon.marvin.io.MolExportException chemaxon.formats.MolExportException
chemaxon.marvin.io.MolExportModule chemaxon.formats.MolExportModule
chemaxon.marvin.io.MolImportModule chemaxon.formats.MolImportModule
chemaxon.marvin.io.MPropHandler chemaxon.formats.MPropHandler
chemaxon.marvin.io.PositionedInputStream chemaxon.formats.PositionedInputStream
chemaxon.marvin.io.formats.MoleculeImporter chemaxon.formats.MoleculeImporter
chemaxon.marvin.io.formats.MoleculeImporterIface chemaxon.formats.MolImporterInterface
chemaxon.marvin.modules.datatransfer.MarvinTransferable chemaxon.marvin.datatransfer.MarvinTransferable
chemaxon.marvin.modules.datatransfer.MTransferable chemaxon.marvin.datatransfer.MTransferable
chemaxon.marvin.modules.datatransfer.TransferableDescriptor chemaxon.marvin.datatransfer.TransferableDescriptor
chemaxon.marvin.paint.DispOptConsts chemaxon.rendering.constants.DispOptConsts
chemaxon.marvin.paint.constants.AnyBondStyle chemaxon.rendering.constants.AnyBondStyle
chemaxon.marvin.paint.constants.CoordinateBondOnMulticenterStyle chemaxon.rendering.constants.CoordinateBondOnMulticenterStyle
chemaxon.marvin.paint.constants.CoordinateBondStyle chemaxon.rendering.constants.CoordinateBondStyle
chemaxon.marvin.paint.constants.RenderingStyle chemaxon.rendering.constants.RenderingStyle
chemaxon.marvin.plugin.CalculatorPlugin chemaxon.calculations.CalculatorPlugin
chemaxon.marvin.plugin.CalculatorPluginService chemaxon.calculations.CalculatorPluginService
chemaxon.marvin.plugin.PluginException chemaxon.calculations.CalculatorPluginException
chemaxon.marvin.plugin.PluginInputCheckerException chemaxon.calculations.CalculatorPluginInputException
chemaxon.marvin.plugin.PluginMDocSource chemaxon.calculations.CalculatorPluginMDocSource
chemaxon.marvin.services.AsyncCallback chemaxon.calculations.services.AsyncCallback
chemaxon.marvin.services.DynamicArgument chemaxon.calculations.services.DynamicArgument
chemaxon.marvin.services.ServiceArgument chemaxon.calculations.services.ServiceArgument
chemaxon.marvin.services.ServiceDescriptor chemaxon.calculations.services.ServiceDescriptor
chemaxon.marvin.services.ServiceDescriptorReader chemaxon.calculations.services.ServiceDescriptorReader
chemaxon.marvin.services.ServiceDescriptorTools chemaxon.calculations.services.ServiceDescriptorTools
chemaxon.marvin.services.ServiceDescriptorWriter chemaxon.calculations.services.ServiceDescriptorWriter
chemaxon.marvin.services.ServiceException chemaxon.calculations.services.ServiceException
chemaxon.marvin.services.ServiceHandler chemaxon.calculations.services.ServiceHandler
chemaxon.marvin.services.httpservice.HTTPServiceDescriptor chemaxon.calculations.services.HttpServiceDescriptor
chemaxon.marvin.services.httpservice.HTTPServiceHandler chemaxon.calculations.services.HttpServiceHandler
chemaxon.marvin.services.json.JsonServiceDescriptor chemaxon.calculations.services.JsonServiceDescriptor
chemaxon.marvin.services.json.JsonServiceHandler chemaxon.calculations.services.JsonServiceHandler
chemaxon.marvin.services.localservice.LocalServiceDescriptor chemaxon.calculations.services.LocalServiceDescriptor
chemaxon.marvin.services.localservice.LocalServiceHandler chemaxon.calculations.services.LocalServiceHandler
chemaxon.marvin.sketch.SketchParameterConstants chemaxon.marvin.common.SketchParameterConstants
chemaxon.marvin.swing.MAction chemaxon.marvin.common.MAction
chemaxon.marvin.util.CleanUtil chemaxon.core.calculations.clean.CleanUtil
chemaxon.marvin.util.OptionDescriptor chemaxon.formats.OptionDescriptor
chemaxon.marvin.view.CellType chemaxon.marvin.common.CellType
chemaxon.marvin.view.MDocStorage chemaxon.marvin.common.MDocStorage
chemaxon.marvin.view.ViewParameterConstants chemaxon.marvin.common.ViewParameterConstants
chemaxon.marvin.view.swing.TableOptions chemaxon.marvin.common.TableOptions
chemaxon.marvin.view.swing.TableSupport chemaxon.marvin.common.TableSupport
chemaxon.naming.document.annotate.DocumentAnnotator chemaxon.naming.document.DocumentAnnotator
chemaxon.naming.document.annotate.DocumentAnnotatorOptions chemaxon.naming.document.DocumentAnnotatorOptions
chemaxon.naming.document.annotate.XmlToHtmlConverter chemaxon.naming.document.XmlToHtmlConverter
chemaxon.nfunk.jep.ParseException chemaxon.chemterms.ParseException
chemaxon.pharmacophore.PMap chemaxon.descriptors.pharmacophore.PMap
chemaxon.pharmacophore.PMapper chemaxon.descriptors.pharmacophore.PMapper
chemaxon.pharmacophore.PSymbols chemaxon.descriptors.pharmacophore.PSymbols
chemaxon.sss.SearchConstants chemaxon.search.api.SearchConstants
chemaxon.sss.formula.FormulaSearch chemaxon.search.FormulaSearch
chemaxon.sss.screen.HashCode chemaxon.search.util.HashCode
chemaxon.sss.screen.Similarity chemaxon.search.util.SimilarityUtil
chemaxon.sss.screen.StrucFPConfig chemaxon.jchem.db.StructuralKeyConfig
chemaxon.sss.search.Decomposition chemaxon.search.Decomposition
chemaxon.sss.search.JChemSearchOptions chemaxon.jchem.db.JChemSearchOptions
chemaxon.sss.search.MarkushGenerator chemaxon.search.MarkushGenerator
chemaxon.sss.search.MatchCountOptions chemaxon.jchem.db.MatchCountOptions
chemaxon.sss.search.MolComparator chemaxon.search.api.MolComparator
chemaxon.sss.search.MolSearch chemaxon.search.MolSearch
chemaxon.sss.search.MolSearchOptions chemaxon.search.api.options.MolSearchOptions
chemaxon.sss.search.RgDecompResults chemaxon.search.RgroupDecompositionResults
chemaxon.sss.search.RGroupDecomposition chemaxon.search.RgroupDecomposition
chemaxon.sss.search.SearchException chemaxon.search.api.SearchException
chemaxon.sss.search.SearchHit chemaxon.search.api.SearchHit
chemaxon.sss.search.SearchOptions chemaxon.search.api.options.SearchOptions
chemaxon.sss.search.SearchTimeoutException chemaxon.search.api.SearchTimeoutException
chemaxon.sss.search.StandardizedMolSearch chemaxon.search.StandardizedMolSearch
chemaxon.sss.search.UnsupportedQueryException chemaxon.search.api.UnsupportedQueryException
chemaxon.sss.search.options.HaltOnErrorOption chemaxon.search.api.options.HaltOnErrorOption
chemaxon.sss.search.options.HasOptionString chemaxon.search.api.options.OptionStringProvider
chemaxon.sss.search.options.HomologyTranslationOption chemaxon.search.api.options.HomologyTranslationOption
chemaxon.sss.search.options.MarkushAromaticityHandlingOption chemaxon.search.api.options.MarkushAromaticityHandlingOption
chemaxon.sss.search.options.SetOfSmallestRingsOption chemaxon.search.api.options.SetOfSmallestRingsOption
chemaxon.sss.search.options.TargetHomologyMatchingMode chemaxon.search.api.options.TargetHomologyMatchingMode
chemaxon.sss.search.options.TautomerEqualityMode chemaxon.search.api.options.TautomerEqualityMode
chemaxon.sss.search.options.TautomerSubstructureMode chemaxon.search.api.options.TautomerSubstructureMode
chemaxon.sss.search.options.TautomerTransformationMode chemaxon.search.api.options.TautomerTransformationMode
chemaxon.standardizer.Persistent chemaxon.standardizer.PersistentProperty
chemaxon.standardizer.actions.AbstractSgroupAction chemaxon.standardizer.AbstractSgroupAction
chemaxon.standardizer.advancedactions.Clean2DAction chemaxon.standardizer.actions.Clean2DAction
chemaxon.standardizer.advancedactions.Clean3DAction chemaxon.standardizer.actions.Clean3DAction
chemaxon.standardizer.advancedactions.CreateGroupAction chemaxon.standardizer.actions.CreateGroupAction
chemaxon.standardizer.advancedactions.GroupDefinition chemaxon.standardizer.actions.GroupDefinition
chemaxon.standardizer.advancedactions.RemoveSolventsAction chemaxon.standardizer.actions.RemoveSolventsAction
chemaxon.standardizer.advancedactions.StripSaltsAction chemaxon.standardizer.actions.StripSaltsAction
chemaxon.standardizer.advancedactions.TransformAction chemaxon.standardizer.actions.TransformAction
chemaxon.standardizer.configuration.reader.StandardizerActionStringReader chemaxon.standardizer.configuration.StandardizerActionStringReader
chemaxon.standardizer.configuration.reader.StandardizerConfigurationReader chemaxon.standardizer.configuration.StandardizerConfigurationReader
chemaxon.standardizer.configuration.reader.StandardizerXMLReader chemaxon.standardizer.configuration.StandardizerConfigurationXmlReader
chemaxon.standardizer.configuration.writer.StandardizerActionStringWriter chemaxon.standardizer.configuration.StandardizerActionStringWriter
chemaxon.standardizer.configuration.writer.StandardizerConfigurationWriter chemaxon.standardizer.configuration.StandardizerConfigurationWriter
chemaxon.standardizer.configuration.writer.StandardizerXMLWriter chemaxon.standardizer.configuration.StandardizerConfigurationXmlWriter
chemaxon.struc.AbstractAtropStereoDescriptor chemaxon.core.calculations.stereo.AbstractAtropStereoDescriptor
chemaxon.struc.AbstractAxialStereoDescriptor chemaxon.core.calculations.stereo.AbstractAxialStereoDescriptor
chemaxon.struc.AbstractCisTransStereoDescriptor chemaxon.core.calculations.stereo.AbstractCisTransStereoDescriptor
chemaxon.struc.AbstractTetrahedralStereoDescriptor chemaxon.core.calculations.stereo.AbstractTetrahedralStereoDescriptor
chemaxon.struc.AtomProperty.Radical chemaxon.struc.Radical
chemaxon.struc.AtropStereoDescriptor chemaxon.core.calculations.stereo.AtropStereoDescriptor
chemaxon.struc.AtropStereoIUPACDescriptor chemaxon.core.calculations.stereo.AtropStereoIUPACDescriptor
chemaxon.struc.AxialStereoDescriptor chemaxon.core.calculations.stereo.AxialStereoDescriptor
chemaxon.struc.AxialStereoIUPACDescriptor chemaxon.core.calculations.stereo.AxialStereoIUPACDescriptor
chemaxon.struc.CisTransStereoDescriptor chemaxon.core.calculations.stereo.CisTransStereoDescriptor
chemaxon.struc.CisTransStereoIUPACDescriptor chemaxon.core.calculations.stereo.CisTransStereoIUPACDescriptor
chemaxon.struc.CIPStereoDescriptorIface chemaxon.core.calculations.stereo.CIPStereoDescriptor
chemaxon.struc.CIPStereoDescriptorIface.CIPType chemaxon.core.calculations.stereo.CIPStereoType
chemaxon.struc.CIPStereoDescriptorIface.CIPValue chemaxon.core.calculations.stereo.CIPStereoValue
chemaxon.struc.CTransform3D chemaxon.struc.Transform3D
chemaxon.struc.DPoint3 chemaxon.struc.Point3D
chemaxon.struc.PeriodicSystem chemaxon.struc.PeriodicTable
chemaxon.struc.RgMoleculeGraphIface chemaxon.struc.RgMoleculeGraph
chemaxon.struc.StereoActivePart chemaxon.core.calculations.stereo.StereoActivePart
chemaxon.struc.TetrahedralStereoDescriptor chemaxon.core.calculations.stereo.TetrahedralStereoDescriptor
chemaxon.struc.TetrahedralStereoIUPACDescriptor chemaxon.core.calculations.stereo.TetrahedralStereoIUPACDescriptor
chemaxon.struc.graphics.analysis.MAnalysisBoxTerm chemaxon.struc.graphics.MAnalysisBoxTerm
chemaxon.struc.stereo.EZConfiguration chemaxon.struc.EZConfiguration
chemaxon.structurechecker.factory.CheckerFixerFactory chemaxon.structurechecker.CheckerFixerFactory
chemaxon.util.ConnectionHandler chemaxon.jchem.util.ConnectionHandler
chemaxon.util.DatabaseTools chemaxon.jchem.db.DatabaseTools
chemaxon.util.ErrorHandler chemaxon.jchem.util.ErrorHandler
chemaxon.util.ErrorProcessor chemaxon.formats.ErrorProcessor
chemaxon.util.HitColoringAndAlignmentOptions chemaxon.search.hitdisplay.HitDisplayOptions
chemaxon.util.HitDisplayTool chemaxon.search.hitdisplay.HitDisplayTool
chemaxon.util.HitDisplayUtil chemaxon.search.hitdisplay.HitDisplayUtil
chemaxon.util.ImageExportUtil chemaxon.marvin.util.ImageExportUtil
chemaxon.util.MolFilter chemaxon.core.util.MolFilter
chemaxon.util.MolHandler chemaxon.jchem.db.MolHandler
chemaxon.util.ValenceFilter chemaxon.core.util.ValenceFilter
chemaxon.util.iterator.IteratorFactory chemaxon.struc.IteratorFactory
chemaxon.util.iterator.MoleculeIterator chemaxon.formats.MoleculeIterator
chemaxon.util.iterator.MoleculeIteratorFactory chemaxon.formats.MoleculeIteratorFactory
chemaxon.util.progress.ProgressObserver chemaxon.clustering.common.ProgressObserver
com.chemaxon.calculations.admet.HergActivityPrediction chemaxon.calculations.admet.HergActivityPrediction
com.chemaxon.calculations.admet.HergActivityPredictor chemaxon.calculations.admet.HergActivityPredictor
com.chemaxon.calculations.admet.HergClass chemaxon.calculations.admet.HergClass
com.chemaxon.calculations.admet.HergClassPrediction chemaxon.calculations.admet.HergClassPrediction
com.chemaxon.calculations.admet.HergClassPredictor chemaxon.calculations.admet.HergClassPredictor
com.chemaxon.calculations.cli.CalculatorPluginOutput chemaxon.calculations.output.CalculatorPluginOutput
com.chemaxon.calculations.cli.CalculatorResultAccess chemaxon.calculations.output.CalculatorPluginOutputAccess
com.chemaxon.calculations.elemanal.ElementalAnalysis chemaxon.calculations.elemental.ElementalAnalysis
com.chemaxon.calculations.elemanal.FormulaGenerationRule chemaxon.calculations.elemental.FormulaGenerationRule
com.chemaxon.calculations.elemanal.factory.ElementalAnalysisFactory chemaxon.calculations.elemental.ElementalAnalysisFactory
com.chemaxon.calculations.elemanal.formula.FormulaAtom chemaxon.calculations.elemental.FormulaAtom
com.chemaxon.calculations.gui.CalculatorPluginDisplay chemaxon.calculations.gui.CalculatorPluginDisplay
com.chemaxon.calculations.gui.MChart chemaxon.calculations.gui.MChart
com.chemaxon.calculations.gui.ParameterPanelHandler chemaxon.calculations.gui.ParameterPanelHandler
com.chemaxon.calculations.gui.PluginFactory chemaxon.calculations.gui.PluginFactory
com.chemaxon.calculations.solubility.DefaultSolubilityCategory chemaxon.calculations.solubility.DefaultSolubilityCategory
com.chemaxon.calculations.solubility.SolubilityCalculator chemaxon.calculations.solubility.SolubilityCalculator
com.chemaxon.calculations.solubility.SolubilityCategories chemaxon.calculations.solubility.SolubilityCategories
com.chemaxon.calculations.solubility.SolubilityCategory chemaxon.calculations.solubility.SolubilityCategory
com.chemaxon.calculations.solubility.SolubilityResult chemaxon.calculations.solubility.SolubilityResult
com.chemaxon.calculations.solubility.SolubilityUnit chemaxon.calculations.solubility.SolubilityUnit
com.chemaxon.calculations.stereoanal.ErrorReport chemaxon.calculations.stereo.ErrorReport
com.chemaxon.calculations.stereoanal.StereoAnalysis chemaxon.calculations.stereo.StereoAnalysis
com.chemaxon.calculations.stereoanal.StereoConstants.EnhancedStereoType chemaxon.calculations.stereo.stereocenters.EnhancedStereoType
com.chemaxon.calculations.stereoanal.filters.StereoCenterVisitor chemaxon.calculations.stereo.stereocenters.StereoCenterVisitor
com.chemaxon.calculations.stereoanal.stereocenters.AtomSelection chemaxon.calculations.stereo.stereocenters.AtomSelection
com.chemaxon.calculations.stereoanal.stereocenters.AtropStereoCenter chemaxon.calculations.stereo.stereocenters.AtropStereoCenter
com.chemaxon.calculations.stereoanal.stereocenters.AttachedData chemaxon.calculations.stereo.stereocenters.AttachedData
com.chemaxon.calculations.stereoanal.stereocenters.AxialStereoCenter chemaxon.calculations.stereo.stereocenters.AxialStereoCenter
com.chemaxon.calculations.stereoanal.stereocenters.CisTransStereoCenter chemaxon.calculations.stereo.stereocenters.CisTransStereoCenter
com.chemaxon.calculations.stereoanal.stereocenters.EnhancedStereo chemaxon.calculations.stereo.stereocenters.EnhancedStereo
com.chemaxon.calculations.stereoanal.stereocenters.EnhancedStereoGroup chemaxon.calculations.stereo.stereocenters.EnhancedStereoGroup
com.chemaxon.calculations.stereoanal.stereocenters.StereoCenter chemaxon.calculations.stereo.stereocenters.StereoCenter
com.chemaxon.calculations.stereoanal.stereocenters.TetrahedralStereoCenter chemaxon.calculations.stereo.stereocenters.TetrahedralStereoCenter
com.chemaxon.calculations.stereoisomers.StereoisomerEnumeration chemaxon.calculations.stereo.StereoisomerEnumeration
com.chemaxon.calculations.stereoisomers.StereoisomerSettings chemaxon.calculations.stereo.StereoisomerSettings
com.chemaxon.clustering.common.Cluster chemaxon.clustering.common.Cluster
com.chemaxon.clustering.common.DissimilarityInput chemaxon.clustering.common.DissimilarityInput
com.chemaxon.clustering.common.HierarchicCluster chemaxon.clustering.common.HierarchicCluster
com.chemaxon.clustering.common.HierarchicClustering chemaxon.clustering.common.HierarchicClustering
com.chemaxon.clustering.common.IDBasedAssigner chemaxon.clustering.common.IDBasedAssigner
com.chemaxon.clustering.common.IDBasedAssignerBuilder chemaxon.clustering.common.IDBasedAssignerBuilder
com.chemaxon.clustering.common.IDBasedClusterBuilder chemaxon.clustering.common.IDBasedClusterBuilder
com.chemaxon.clustering.common.IDBasedClusterBuilderSpec chemaxon.clustering.common.IDBasedClusterBuilderSpec
com.chemaxon.clustering.common.IDBasedHierarchicCluster chemaxon.clustering.common.IDBasedHierarchicCluster
com.chemaxon.clustering.common.IDBasedHierarchicClusterBuilder chemaxon.clustering.common.IDBasedHierarchicClusterBuilder
com.chemaxon.clustering.common.IDBasedHierarchicClustering chemaxon.clustering.common.IDBasedHierarchicClustering
com.chemaxon.clustering.common.IDBasedHierarchy chemaxon.clustering.common.IDBasedHierarchy
com.chemaxon.clustering.common.IDBasedSingleLevelClustering chemaxon.clustering.common.IDBasedSingleLevelClustering
com.chemaxon.clustering.common.LevelAssigner chemaxon.clustering.common.LevelAssigner
com.chemaxon.clustering.common.PhasedProgressObserver chemaxon.clustering.common.PhasedProgressObserver
com.chemaxon.clustering.common.ProgressObserver chemaxon.clustering.common.ProgressObserver
com.chemaxon.clustering.common.SingleLevelClustering chemaxon.clustering.common.SingleLevelClustering
com.chemaxon.clustering.framework.BemisMurckoClustering chemaxon.clustering.framework.BemisMurckoClustering
com.chemaxon.clustering.framework.FrameworkClusteringResults chemaxon.clustering.framework.FrameworkClusteringResults
com.chemaxon.clustering.framework.OrderedElement chemaxon.clustering.framework.OrderedElement
com.chemaxon.clustering.singlelinkage.SingleLinkage chemaxon.clustering.SingleLinkageClustering
com.chemaxon.clustering.sphex.SphereExclusion chemaxon.clustering.SphereExclusion
com.chemaxon.clustering.util.ClusteringUtils chemaxon.clustering.util.ClusteringUtils
com.chemaxon.clustering.util.PostOrderDfsVisitor chemaxon.clustering.util.PostOrderDfsVisitor
com.chemaxon.clustering.util.SimpleDfsVisitor chemaxon.clustering.util.SimpleDfsVisitor
com.chemaxon.clustering.wards.LanceWilliamsAlgorithm chemaxon.clustering.LanceWilliamsAlgorithm
com.chemaxon.clustering.wards.LanceWilliamsMerge chemaxon.clustering.LanceWilliamsMerge
com.chemaxon.clustering.wards.LanceWilliamsMerges chemaxon.clustering.LanceWilliamsMerges
com.chemaxon.common.annotations.Beta chemaxon.common.annotations.Beta
com.chemaxon.common.annotations.PublicApi chemaxon.common.annotations.PublicApi
com.chemaxon.common.annotations.RemovalDate chemaxon.common.annotations.RemovalDate
com.chemaxon.common.annotations.SubjectToRemoval chemaxon.common.annotations.SubjectToRemoval
com.chemaxon.mapper.AutoMapper chemaxon.reaction.mapper.AutoMapper
com.chemaxon.search.mcs.MaxCommonSubstructure chemaxon.search.mcs.MaxCommonSubstructure
com.chemaxon.search.mcs.McsCustomMatcher chemaxon.search.mcs.McsCustomMatcher
com.chemaxon.search.mcs.McsCustomMatcherFactory chemaxon.search.mcs.McsCustomMatcherFactory
com.chemaxon.search.mcs.McsSearchOptions chemaxon.search.mcs.McsSearchOptions
com.chemaxon.search.mcs.McsSearchResult chemaxon.search.mcs.McsSearchResult
com.chemaxon.search.mcs.RingHandlingMode chemaxon.search.mcs.RingHandlingMode
com.chemaxon.search.mcs.SearchMode chemaxon.search.mcs.McsSearchMode
com.chemaxon.search.mcs.buildup.BuildupMcs chemaxon.search.mcs.BuildupMcs
com.chemaxon.search.mcs.maxclique.MaxCliqueMcs chemaxon.search.mcs.MaxCliqueMcs
com.chemaxon.version.VersionInfo chemaxon.common.version.VersionInfo
"

# Create backup
TARGET_DIR=$(cd "$TARGET_DIR" && pwd)
TARGET_PARENT=$(dirname "$TARGET_DIR")
TARGET_NAME=$(basename "$TARGET_DIR")
BACKUP_DIR="${TARGET_PARENT}/${TARGET_NAME}_backup_$(date +%Y%m%d_%H%M%S)"

echo "Target directory:   $TARGET_DIR"
echo "Creating backup at: $BACKUP_DIR"
echo ""

cp -r "$TARGET_DIR" "$BACKUP_DIR"

if [ ! -d "$BACKUP_DIR" ] || [ ! "$(ls -A "$BACKUP_DIR")" ]; then
    echo "ERROR: Backup creation failed or backup is empty"
    exit 1
fi

# Counter for changes
TOTAL_FILES=0
MODIFIED_FILES=0
TOTAL_REPLACEMENTS=0

# Variables for global temporary files
PARSED_MAPPINGS=""
PACKAGE_ONLY_SED_SCRIPT=""
CLASS_CHANGE_SED_SCRIPT=""

escape_sed() {
    echo "$1" | sed 's/[./$]/\\&/g'
}

get_simple_class_name() {
    echo "${1##*.}"
}

should_process_file() {
    local file="$1"

    # Skip common generated directories
    [[ "$file" != */.git/* ]] &&
    [[ "$file" != */.gradle/* ]] &&
    [[ "$file" != */.idea/* ]] &&
    [[ "$file" != */.vscode/* ]] &&
    [[ "$file" != */node_modules/* ]]
}

get_sed_word_start() {
    if sed --version 2>/dev/null | head -1 | grep -q GNU; then
        echo "\\b" # for linux (GNU sed)
    else
        echo "[[:<:]]" # for macOS (BSD sed)
    fi
}

get_sed_word_end() {
    if sed --version 2>/dev/null | head -1 | grep -q GNU; then
        echo "\\b" # for linux (GNU sed)
    else
        echo "[[:>:]]" # for macOS (BSD sed)
    fi
}

# Word boundary definitions for sed
WORD_START=$(get_sed_word_start)
WORD_END=$(get_sed_word_end)

parse_mappings() {
    PARSED_MAPPINGS=$(mktemp)

    echo "$MAPPINGS" | while IFS= read -r line; do
        read -r old_class new_class <<< "$line"
        [[ -z "$old_class" || -z "$new_class" ]] && continue

        old_simple=$(get_simple_class_name "$old_class")
        new_simple=$(get_simple_class_name "$new_class")

        if [ "$old_simple" = "$new_simple" ]; then
            echo "PACKAGE_ONLY:$old_class $new_class"
        else
            echo "CLASS_CHANGE:$old_class $new_class"
        fi
    done > "$PARSED_MAPPINGS"
}

create_sed_script() {
    local mapping_type="$1"
    local sed_script=$(mktemp)

    grep "^${mapping_type}:" "$PARSED_MAPPINGS" | while IFS= read -r line; do
        mapping="${line#${mapping_type}:}"
        read -r old_class new_class <<< "$mapping"

        old_class_escaped=$(escape_sed "$old_class")
        new_class_escaped=$(escape_sed "$new_class")

        echo "s/${WORD_START}${old_class_escaped}${WORD_END}/${new_class_escaped}/g" >> "$sed_script"
    done

    echo "$sed_script"
}

create_simple_name_sed_script() {
    local file="$1"
    local sed_script=$(mktemp)

    grep "^CLASS_CHANGE:" "$PARSED_MAPPINGS" | while IFS= read -r line; do
        mapping="${line#CLASS_CHANGE:}"
        read -r old_class new_class <<< "$mapping"

        if grep -q "^ *import *${WORD_START}${new_class}${WORD_END}" "$file" 2>/dev/null; then
            old_simple=$(get_simple_class_name "$old_class")
            new_simple=$(get_simple_class_name "$new_class")
            old_simple_escaped=$(escape_sed "$old_simple")
            new_simple_escaped=$(escape_sed "$new_simple")

            echo "s/${WORD_START}${old_simple_escaped}${WORD_END}/${new_simple_escaped}/g" >> "$sed_script"
        fi
    done

    echo "$sed_script"
}

process_java_file() {
    local file="$1"

    local temp_file=$(mktemp)
    local temp_file2=$(mktemp)
    local needs_simple_name_pass=false

    # Pass 1: Replace package-only changes
    if sed -f "$PACKAGE_ONLY_SED_SCRIPT" "$file" > "$temp_file" 2>/dev/null; then
        # Pass 2: Replace fully qualified names for class name changes
        if sed -f "$CLASS_CHANGE_SED_SCRIPT" "$temp_file" > "$temp_file2" 2>/dev/null; then
            # Check if any class name changes occurred
            if ! cmp -s "$temp_file" "$temp_file2"; then
                needs_simple_name_pass=true
                mv "$temp_file2" "$temp_file"
            else
                rm -f "$temp_file2"
            fi

            # Pass 3: Replace simple names only if class name changes occurred
            if [ "$needs_simple_name_pass" = true ]; then
                local simple_sed_script=$(create_simple_name_sed_script "$temp_file")

                if sed -f "$simple_sed_script" "$temp_file" > "$temp_file2" 2>/dev/null; then
                    mv "$temp_file2" "$temp_file"
                else
                    echo "  Error in simple name changes pass: $file"
                fi
            fi

            # Final comparison and update
            if ! cmp -s "$file" "$temp_file"; then
                local changes=$(diff "$file" "$temp_file" | grep -c '^>' 2>/dev/null || echo "0")
                MODIFIED_FILES=$((MODIFIED_FILES + 1))
                TOTAL_REPLACEMENTS=$((TOTAL_REPLACEMENTS + changes))

                mv "$temp_file" "$file"

                local target_dir_escaped=$(escape_sed "$TARGET_DIR")
                local relative_path=$(echo $file | sed "s/^${target_dir_escaped}.//")
                echo "  Modified: $relative_path (changed lines: $changes)"
            fi
        else
            echo "  Error in class changes pass: $file"
        fi
    else
        echo "  Error in package-only changes pass: $file"
    fi

    # Delete temporary files
    rm -f "$temp_file" "$temp_file2"
}

# Parse mappings into categories
parse_mappings

# Count mapping types for reporting
PACKAGE_ONLY_COUNT=$(grep -c "^PACKAGE_ONLY:" "$PARSED_MAPPINGS" 2>/dev/null || echo "0")
CLASS_CHANGE_COUNT=$(grep -c "^CLASS_CHANGE:" "$PARSED_MAPPINGS" 2>/dev/null || echo "0")

# Create sed scripts
PACKAGE_ONLY_SED_SCRIPT=$(create_sed_script "PACKAGE_ONLY")
CLASS_CHANGE_SED_SCRIPT=$(create_sed_script "CLASS_CHANGE")

# Find and process Java files
echo "Processing Java files..."
while IFS= read -r -d '' file; do
    if should_process_file "$file"; then
        TOTAL_FILES=$((TOTAL_FILES + 1))
        if [ $((TOTAL_FILES % 100)) -eq 0 ]; then
            echo "  Processed $TOTAL_FILES files so far..."
        fi
        process_java_file "$file"
    fi
done < <(find "$TARGET_DIR" -name "*.java" -type f -print0)

# Cleanup temporary files
rm -f "$PARSED_MAPPINGS" "$PACKAGE_ONLY_SED_SCRIPT" "$CLASS_CHANGE_SED_SCRIPT"

# Summary
echo ""
echo "Migration completed!"
echo ""
echo "Processed Java files: $TOTAL_FILES"
echo "Modified Java files:  $MODIFIED_FILES"
echo "Total replacements:   $TOTAL_REPLACEMENTS"
echo "Backup directory:     $BACKUP_DIR"
echo ""

if [ $MODIFIED_FILES -gt 0 ]; then
    echo "IMPORTANT: Please review the changes and test your code."
    echo "If something went wrong, you can restore the files from backup."
else
    echo "No files were modified."
fi
