Variable ProcessName, LogFile, Project, Media, ExecutableName, ProjectFiles, SegmentOrder, CompileOrder, MacsbugSymbols, SmartLink, ProjectName, PictureNumber
ProcessName = Process.Front
If File('ReDMCSB:SOURCE:LOGFILE.TXT').Exists
        LogFile = File('ReDMCSB:SOURCE:LOGFILE.TXT').Text
Else
        LogFile = 'REDMCSB:BUILD:CREATE.LOG'
End If
// Log system information
// Variable ProcessIndex
// For ProcessIndex = 1 to Process.Count
//         File(LogFile).Append = (Date 85) & '_' & (Time 5) & ' ' & Process(ProcessIndex).Name & ' ' & Process(ProcessIndex).Size & ' ' & Process(ProcessIndex).Free & '<return>'
// End For
// Read configuration files
If File('REDMCSB:SOURCE:PROJECT.TXT').Exists
        Project = File('REDMCSB:SOURCE:PROJECT.TXT').Text
Else
        Exit
End If
ListDelimiter = '<return>'
Media = ListItems Project, 1
ExecutableName = ListItems Project, 2
ProjectFiles = ListItems Project, 3
SegmentOrder = ListItems Project, 4
CompileOrder = ListItems Project, 5
MacsbugSymbols = ListItems Project, 6
SmartLink = ListItems Project, 7
ListDelimiter = '='
Media = ListItems Media, 2
ExecutableName = ListItems ExecutableName, 2
ProjectFiles = ListItems ProjectFiles, 2
SegmentOrder = ListItems SegmentOrder, 2
CompileOrder = ListItems CompileOrder, 2
MacsbugSymbols = ListItems MacsbugSymbols, 2
SmartLink = ListItems SmartLink, 2
ProjectName = Media & '_' & ExecutableName & '.Project'

// Create new project
SelectPopUp 120, 25, 'Desktop'
Type 'REDMCSB'
SelectButton 'Open'
Type 'OBJECT'
SelectButton 'Open'
Type Media
SelectButton 'Open'
Type ExecutableName
SelectButton 'Open'
SelectButton 'New'
Type ProjectName
SelectButton 'Create'

// Set project options
SelectMenu 'Edit', 'OptionsÉ'
If ProcessName = 'THINK C'      // THINK C 4.0
        SelectButton 'Code Generation'
        If MacsbugSymbols = 'Enabled'
                SelectButton Check 'Macsbug Symbols'
        Else
                SelectButton Uncheck 'Macsbug Symbols'
        End If
        SelectButton Uncheck '<MacHeaders>'
        SelectButton 'Compiler Flags'
        SelectButton Uncheck 'Check Pointer Types'
End If
If ProcessName = 'THINK C 5.0'
        SelectPopUp 97, 56, 'Preferences'
        SelectButton Check 'Generate link map'
        SelectPopUp 97, 56, 'Language settings'
        SelectButton Uncheck 'Check pointer types'
        SelectButton Uncheck 5  // 'Strict Prototype Enforcement' (not accessible by name)
        SelectPopUp 97, 56, 'Prefix'
        Type Command 'a'
        Type '<delete>'
End If
SelectButton 'OK'

// Add source files in segments
Variable SegmentCount, SegmentIndex, FileCount, SegmentFiles, FileIndex, FileName, FolderCount, FolderIndex, FolderName, CurrentFolder
Variable SortedSegmentFiles, SegmentToSortedFiles
ListDelimiter = ';'
SegmentCount = ListCount ProjectFiles
For SegmentIndex = 1 To SegmentCount
File(LogFile).Append = 'Add files in segment ' & SegmentIndex & '/' & SegmentCount & '<return>'
        SortedSegmentFiles = ''
        SelectMenu 'Source', 'AddÉ'

        ListDelimiter = ';'
        SegmentFiles = ListItems ProjectFiles, SegmentIndex
        ListDelimiter = ','
        FileCount = ListCount SegmentFiles
        For FileIndex = 1 To FileCount
                FileName = ListItems SegmentFiles, FileIndex
                If (Find ':', FileName) = 0 // If the entry is a file name
                        If File(CurrentFolder & ':' & FileName).Exists
                                If SortedSegmentFiles = ''
                                        SortedSegmentFiles = FileName
                                Else
                                        SortedSegmentFiles = SortedSegmentFiles & ',' & FileName
                                End If
                                Type FileName
File(LogFile).Append = 'Add file: ' & FileName & '<return>'
                                If ProcessName = 'THINK C 5.0'
                                        Pause 10
                                End If
                                SelectButton 'Add'
                        Else
                                File(LogFile).Append = 'Error while adding project files: file not found [' & CurrentFolder & ':' & FileName & ']<return>'
                        End If
                Else // If the entry is a folder path (contains ':' character)
                        CurrentFolder = FileName
                        If File(CurrentFolder).Exists
                                SelectPopUp 120, 25, 'Desktop'
File(LogFile).Append = 'Open folder: Desktop:'
                                If ProcessName = 'THINK C 5.0'
                                        Pause 10
                                End If
                                ListDelimiter = ':'
                                FolderCount = ListCount CurrentFolder
                                For FolderIndex = 1 To FolderCount
                                        FolderName = ListItems CurrentFolder, FolderIndex
                                        Type FolderName
File(LogFile).Append = FolderName & ':'
                                        If ProcessName = 'THINK C 5.0'
                                                Pause 10
                                        End If
                                        If DialogButton('Open').Enabled
                                                SelectButton 'Open'  // THINK C 5.0
                                        Else
                                                SelectButton 'Add'   // THINK C 4.0
                                        End If
                                End For
File(LogFile).Append = '<return>'
                                ListDelimiter = ','
                        Else
                                File(LogFile).Append = 'Error while adding project files: folder not found [' & CurrentFolder & ']<return>'
                        End If
                End If
        End For
        If DialogButton('Done').Enabled
                SelectButton 'Done'     // THINK C 5.0
        Else
                SelectButton 'Cancel'   // THINK C 4.0 or THINK C 5.0 if no file was added
        End If
        SortedSegmentFiles = ListSort SortedSegmentFiles
        If SegmentToSortedFiles = ''
                SegmentToSortedFiles = SortedSegmentFiles
        Else
                SegmentToSortedFiles = SegmentToSortedFiles & ';' & SortedSegmentFiles
        End If

        // If not the last segment then move to a new segment
        If NOT (SegmentIndex = SegmentCount)
                Repeat 15
                        Scroll Page Down ProjectName
                End Repeat
                // Click in the last line of the window
                Click Window('ProjectName').Left + (Window('ProjectName').Width / 2), Window('ProjectName').Top + Window('ProjectName').Height - 7
        End If
End For

// Reorder segments with mouse drag and drop
Variable FileNameHeight, WindowHeaderHeight, VisibleFileCount, SegmentToMove, CurrentSegmentIndex, CurrentSegmentOrder, SortedProjectFiles, MouseX, MouseFromY, MouseToY
FileNameHeight = 14
// WindowHeaderHeight = 35 // Global
WindowHeaderHeight = 15

// Number of file names visible in the project window
VisibleFileCount = (Window(ProjectName).Height - 35) / 14
MouseX = (Window(ProjectName).Width / 2)

// Initialize current segment order
ListDelimiter = ','
For SegmentIndex = 1 To ListCount SegmentOrder
        If CurrentSegmentOrder = ''
                CurrentSegmentOrder = SegmentIndex
        Else
                CurrentSegmentOrder = CurrentSegmentOrder & ',' & SegmentIndex
        End If
End For

//File(LogFile).Append = 'SegmentOrder:' & SegmentOrder & '<return>'
//File(LogFile).Append = 'CurrentSegmentOrder:' & CurrentSegmentOrder & '<return>'
//File(LogFile).Append = 'SegmentToSortedFiles:' & SegmentToSortedFiles & '<return>'
//PictureNumber = 1

// Loop to swap segments until they are sorted in the expected order
While NOT (CurrentSegmentOrder = SegmentOrder)
//File(LogFile).Append = 'Entering swap segment loop' & '<return>'
        // Find segment to move
        ListDelimiter = ','
        For SegmentIndex = 1 To SegmentCount
//File(LogFile).Append = 'SegmentIndex:' & SegmentIndex & '<return>'
                If NOT ((ListItems CurrentSegmentOrder, SegmentIndex) = (ListItems SegmentOrder, SegmentIndex))
                        Exit For
                End If
        End For
        SegmentToMove = ListItems SegmentOrder, SegmentIndex
//File(LogFile).Append = 'SegmentToMove:' & SegmentToMove & ' (SegmentIndex: ' & SegmentIndex & ') <return>'

        // Get name of the first file in the segment to move
        ListDelimiter = ';'
        FileName = ListItems SegmentToSortedFiles, SegmentToMove
//File(LogFile).Append = 'FileName:' & FileName & '<return>'
        ListDelimiter = ','
        FileName = ListItems FileName, 1
//File(LogFile).Append = 'FileName:' & FileName & '<return>'

        // Build same list of file names as visible in the project window
        SortedProjectFiles = ''
        For SegmentIndex = 1 To SegmentCount
                ListDelimiter = ','
                CurrentSegmentIndex = ListItems CurrentSegmentOrder, SegmentIndex
//File(LogFile).Append = 'Build SortedProjectFiles - SegmentIndex:' & SegmentIndex & '<return>'
//File(LogFile).Append = 'Build SortedProjectFiles - CurrentSegmentIndex:' & CurrentSegmentIndex & '<return>'
                ListDelimiter = ';'
                SortedSegmentFiles = ListItems SegmentToSortedFiles, CurrentSegmentIndex
//File(LogFile).Append = 'Build SortedProjectFiles - SortedSegmentFiles:' & SortedSegmentFiles & '<return>'
                If SortedProjectFiles = ''
                        SortedProjectFiles = SortedSegmentFiles
                Else
                        SortedProjectFiles = SortedProjectFiles & ',' & SortedSegmentFiles
                End If
//File(LogFile).Append = 'SortedProjectFiles:' & SortedProjectFiles & '<return>'

        End For
//File(LogFile).Append = 'Final SortedProjectFiles:' & SortedProjectFiles & '<return>'

        // Scroll to the top of the project window
        Window(ProjectName).Front
//        Repeat 15
//                Scroll Page Up ProjectName
//        End Repeat
        // Select first file in project window then select first file of segment to move
        Type (ListItems SortedProjectFiles, 1)
        Click MouseX, WindowHeaderHeight + (FileNameHeight / 2)

        // Get mouse coordinates to click on the file to move in the project window
        FileIndex = ListFinder ',', FileName, (SortedProjectFiles & ',')        // ListFinder does not find the last item in a list if it is not followed by the delimiter
//File(LogFile).Append = 'FileIndex:' & FileIndex & ' (VisibleFileCount = ' & VisibleFileCount & ')<return>'
        //Type FileName
        Repeat FileIndex - 1
                Type '<downarrow>'
        End Repeat
        
        // Typing a visible file name in the list highlights it at its current position
        // Typing an invisible file name in the list highlights it and moves it to the first position in the list
        If FileIndex > VisibleFileCount
//                Type '<uparrow>'  // Move one line above to make the destination segment visible
//                FileIndex = 2
                FileIndex = VisibleFileCount
        End If
//File(LogFile).Append = 'FileIndex:' & FileIndex & '<return>'
        MouseFromY = WindowHeaderHeight + (FileIndex * FileNameHeight) - (FileNameHeight / 2)
        MouseToY = MouseFromY - FileNameHeight
//File(LogFile).Append = 'MouseX:' & MouseX & '<return>'
//File(LogFile).Append = 'MouseFromY:' & MouseFromY & '<return>'
//File(LogFile).Append = 'MouseToY:' & MouseToY & '<return>'

//File(LogFile).Append = 'Screenshot ' & PictureNumber & '<return>'
//PictureNumber = PictureNumber + 1
//FKey '3'        // Take a screenshot

        // Swap segment to move with the previous segment
        Click Command MouseX, MouseFromY, MouseX, MouseToY      // Coordinates relative to project window

//File(LogFile).Append = 'Screenshot ' & PictureNumber & '<return>'
//PictureNumber = PictureNumber + 1
//FKey '3'        // Take a screenshot

        // Update current segment order
//File(LogFile).Append = 'Update: CurrentSegmentOrder:' & CurrentSegmentOrder & '<return>'
//File(LogFile).Append = 'Update: SegmentToMove:' & SegmentToMove & '<return>'
        SegmentIndex = ListFinder ',', SegmentToMove, (CurrentSegmentOrder & ',')       // ListFinder does not find the last item in a list if it is not followed by the delimiter
//File(LogFile).Append = 'Update: SegmentIndex:' & SegmentIndex & '<return>'
        ListDelimiter = ','
        CurrentSegmentOrder = ListDelete CurrentSegmentOrder, SegmentIndex, SegmentIndex
//File(LogFile).Append = 'Update (after delete): CurrentSegmentOrder:' & CurrentSegmentOrder & '<return>'
        CurrentSegmentOrder = ListInsert CurrentSegmentOrder, SegmentToMove, SegmentIndex - 1
//File(LogFile).Append = 'Update (after insert): CurrentSegmentOrder:' & CurrentSegmentOrder & '<return>'
//File(LogFile).Append = 'Updated CurrentSegmentOrder:' & CurrentSegmentOrder & '<return>'
End While

// Compile source files in order
Variable BeforeWindowCount, AfterWindowCount, CompileError
CompileError = 'False'
ListDelimiter = ','
FileCount = ListCount CompileOrder
For FileIndex = 1 To FileCount
        BeforeWindowCount = ListCount Window.List
        Window(ProjectName).Front
        FileName = ListItems CompileOrder, FileIndex
        Type FileName
        SelectMenu 'Source'     // Causes update of menu status (enabled/disable)
        If Menu('Source', 'Compile').Enabled
File(LogFile).Append = 'Compile: ' & FileName & '<return>'
                SelectMenu 'Source', 'Compile'
        Else If Menu('Source', 'Load Library').Enabled
File(LogFile).Append = 'Load Library: ' & FileName & '<return>'
                SelectMenu 'Source', 'Load Library'
        End If
        AfterWindowCount = ListCount Window.List
        If NOT (AfterWindowCount = BeforeWindowCount)         // If compile error
                PictureNumber = 1
                While File('REDMCSB:Picture ' & PictureNumber).Exists
                        PictureNumber = PictureNumber + 1
                End While
                FKey '3'        // Take a screenshot
                //FileName = ListItems Window.List, 1
                File(LogFile).Append = 'Compile error in project ' & ProjectName & ' in file ' & FileName & '. See screenshot of error message in file Picture_' & PictureNumber & '.bmp<return>'
                CompileError = 'True'
                CloseWindow // Close compile error message
                Window('REDMCSB:SOURCE:' & FileName).Front
                If Window.Front = ('REDMCSB:SOURCE:' & FileName)
                        CloseWindow // Close source code window
                End If
        End If
End For

// Build application
If CompileError = 'False'
        SelectMenu 'Project', 'Build ApplicationÉ'
        If NOT Window('Link Errors').Visible     // If no link error (the window always exists but is only visible in case of link error)
                // Browse to destination folder and save executable
                SelectPopUp 104, 15, 'Desktop'
                Type '	'
                Type 'REDMCSB'
                SelectButton 'Open'
                Type 'BUILD'
                SelectButton 'Open'
                Type Media
                SelectButton 'Open'
                Type '	'
                Type ExecutableName & '.MAC'
                If SmartLink = 'Enabled'
                        SelectButton Check 'Smart Link'
                Else
                        SelectButton Uncheck 'Smart Link'
                End If
                SelectButton 'Save'
                If DialogButton('Replace').Enabled
                        SelectButton 'Replace'
                End If
        Else
                CloseWindow // Close link error message
                Window('Link Errors').Front
                SelectMenu 'Edit', 'Select All'
                SelectMenu 'Edit', 'Copy'
                ConvertClip
                File(LogFile).Append = 'Link errors in project ' & ProjectName & ':<return>' & Clipboard & '<return>'
                Clipboard = ''
        End If
End If
Window(ProjectName).Front
SelectMenu 'File', 'Quit'
