#! /bin/sh
# (next line not seen by tcl) \
exec tclsh $0 ${1+"$@"}    # goto tcl

### mkbothlut, marty sereno, version 0.1, 20 Jan 2025
# 250120: first hack
# 250129: fix Unknown to be like fs LUTs: ??? 255 255 255 -> Unknown 0 0 0 0

### parms
set tabchar 30        ;# begin names col to begin colors col
set checkuniqflag 1

### help
if {$argc != 1} {
  puts ""
  puts "  Use: cd \$CSURF_DIR/lib/lut"
  puts "       mkbothlut CsurfColorLUT.txt"
  puts "                *or*"
  puts "       mkbothlut HCP-MMP1ColorLUT.txt   \[looks for 2 files lh-*,rh-*\]"
  puts ""
  puts \
    "  Make hemi-uniq idnums/names/cols from ONE hemi-agnostic csurf color LUT:"
  puts "    (1) add max LH region idnum to RH region idnums (LH then RH)"
  puts "    (2) prefix region names w/L_,R_ (LH is 1st)"
  puts "    (3) add 1 to r/red region color"
  puts ""
  puts "            *or*"
  puts ""
  puts "  Make hemi-uniq idnums from TWO HCP-MMP1 color LUTs (rh-,lh- prefix):"
  puts "    (1) concat files (rename from *.ctab scriptsdir outp on read annot)"
  puts "    (2) add max LH region idnum to RH region idnums (LH then RH)"
  puts ""
  puts "  outfile: CsurfColorLUT-both.txt"
  puts "                *or*"
  puts "  outfile: HCP-MMP1ColorLUT-both.txt"
  puts ""
  exit
}

### check input(s)
set skip_rename_recolflag 0  ;# noskip=Csurf, skip=HCP
set infile [lindex $argv 0]
if [string match "*FreeSurferColorLUT.txt" $infile] {          ;# FreeSurfer
  puts "\nmkbothlut: FreeSurferColorLUT.txt: already hemi-unique\n"
  exit
} elseif { [string match "*CsurfColorLUT.txt" $infile] } {     ;# Csurf
  if ![file exists $infile] {
    puts "\nmkbothlut: ### infile: $infile not found  ...quitting\n"
    exit
  }
} elseif { [string match "*HCP-MMP1ColorLUT.txt" $infile] } {  ;# HCP-MMP1
  if { ![file exists rh-$infile] || ![file exists lh-$infile] } {
    puts "\nmkbothlut: ### pair of rh-,lh- prefix files not found ...quitting\n"
    exit
  }
  set skip_rename_recolflag 1
  puts "\nmkbothlut: HCP-MMP1ColorLUT.txt: skip prefix region names, RH red+1\n"
} else {
  puts \
   "\nmkbothlut: ### bad type (not CsurfColorLUT.txt or HCP-MMP1ColorLUT.txt)\n"
  exit
}
set outfile [file rootname $infile]-both.txt

### confirm overwrite
if [file exists $outfile] {
  puts "\nfile $outfile exists, overwrite? (Y/n)"
  set resp [read stdin 1]
  if {"$resp" == "n" || "$resp" == "N"} {puts "$outfile not overwritten"; exit}
}

### go: read file(s), write file, check unique cols
if {!$skip_rename_recolflag} {

  ### CsurfColorLUT.txt
  # read one file to lists
  set i 0
  set idnums {}
  set names {}
  set rs {}
  set gs {}
  set bs {}
  set as {}
  set id [open $infile r]
  foreach line [split [read $id] "\n"] {
    if [string match "#*" $line] { continue }
    if [string match "" $line] { continue }
    lappend idnums [lindex $line 0]
    lappend names  [lindex $line 1]
    lappend rs     [lindex $line 2]
    lappend gs     [lindex $line 3]
    lappend bs     [lindex $line 4]
    lappend as     [lindex $line 5]
    incr i
  }
  close $id
  set maxid $i
  puts "\nmkbothlut: found $maxid regions (including Unknown)\n"
  
  # write hemi-uniq file, start with LH
  set id [open $outfile w 0666]
  set firstline \
    "#!ascii , hemisphere-unique version of $infile (RH, LH+maxid w/r+1"
  puts $firstline
  puts $id $firstline
  for {set i 0} {$i < $maxid} {incr i} {
    set newidnum $i
    set newname L_[lindex $names $i]
    set newcolor "[format %3s [lindex $rs $i]] \
                  [format %3s [lindex $gs $i]] \
                  [format %3s [lindex $bs $i]] \
                  [format %2s [lindex $as $i]]"  
    set spacer ""
    for {set j 0} {$j < [expr $tabchar - [string length $newname]]} {incr j} {
      set spacer "$spacer " 
    }
    set line "$newidnum\t$newname$spacer$newcolor"
    puts $line
    puts $id $line
  }
  # append RH
  for {set i 0} {$i < $maxid} {incr i} {
    if { [lindex $idnums $i] == 0 } { continue }  ;# skip (no repeat) 0=Unknown
    set newidnum [expr $i + $maxid - 1]   ;# maxid-1 is largest region idnum
    set newname R_[lindex $names $i]
    set newcolor "[format %3s [expr [lindex $rs $i] + 1]] \
                  [format %3s [lindex $gs $i]] \
                  [format %3s [lindex $bs $i]] \
                  [format %2s [lindex $as $i]]"  
    set spacer ""
    for {set j 0} {$j < [expr 30 - [string length $newname]]} {incr j} {
      set spacer "$spacer " 
    }
    set line "$newidnum\t$newname$spacer$newcolor"
    puts $line
    puts $id $line
  }
  close $id

} else {

  ### MMP1ColorLUT.txt
  set names {}
  set rs {}
  set gs {}
  set bs {}
  set as {}

  # read LH file to lists
  set i 0
  set id [open lh-$infile r]
  foreach line [split [read $id] "\n"] {
    if [string match "#*" $line] { continue }
    if [string match "" $line] { continue }
    if [string match "\?\?\?" [lindex $line 1]] { ;# ??? -> fs lut for tkmedit
      lappend names  Unknown
      lappend rs     0
      lappend gs     0
      lappend bs     0
      lappend as     0
    } else {
      # ignores idnum [lindex $line 0] since already renumbered
      lappend names  [lindex $line 1]
      lappend rs     [lindex $line 2]
      lappend gs     [lindex $line 3]
      lappend bs     [lindex $line 4]
      lappend as     [lindex $line 5]
    }
    incr i
  }
  close $id
  puts "\nmkbothlut: found $i LH regions (including Unknown)\n"

  # append RH file to lists, skipping 0=Unknown
  set j 0
  set id [open rh-$infile r]
  foreach line [split [read $id] "\n"] {
    if [string match "#*" $line] { continue }
    if [string match "" $line] { continue }
    if { [lindex $line 0] == 0 } { continue }  ;# skip (don't repeat) 0=Unknown
    # ignore idnum [lindex $line 0] since renumbered
    lappend names  [lindex $line 1]
    lappend rs     [lindex $line 2]
    lappend gs     [lindex $line 3]
    lappend bs     [lindex $line 4]
    lappend as     [lindex $line 5]
    incr j 
  }
  close $id
  puts "\nmkbothlut: found $j RH regions, NOT (re)including 0=Unknown\n"

  # write hemi-uniq file
  set maxid [expr $i + $j]
  set id [open $outfile w 0666]
  set firstline \
    "#!ascii , hemisphere-unique version of lh-$infile plus rh-$infile"
  puts $firstline
  puts $id $firstline
  for {set i 0} {$i < $maxid} {incr i} {
    set newidnum $i
    set name [lindex $names $i]
    set spacer ""
    for {set j 0} {$j < [expr $tabchar - [string length $name]]} {incr j} {
      set spacer "$spacer "
    }
    set color "[format %3s [lindex $rs $i]] \
               [format %3s [lindex $gs $i]] \
               [format %3s [lindex $bs $i]] \
               [format %2s [lindex $as $i]]"
    set line "$newidnum\t$name$spacer$color"
    puts $line
    puts $id $line
  }
}

### verify uniq colors in sequentialized/re-colored output (Csurf: r+1 worked)
if {$checkuniqflag} {
  set foundoneflag 0
  set i 0
  set uniqidnums {}
  set uniqnames {}
  set uniqrs {}
  set uniqgs {}
  set uniqbs {}
  set id [open $outfile r]
  foreach line [split [read $id] "\n"] {
    if [string match "#*" $line] { continue }
    if [string match "" $line] { continue }
    set idnum [lindex $line 0]
    set name  [lindex $line 1]
    set r     [lindex $line 2]
    set g     [lindex $line 3]
    set b     [lindex $line 4]
    set j 0
    set found 0
    foreach uniqidnum $uniqidnums {
      set uniqname [lindex $uniqnames $j]
      set uniqr    [lindex $uniqrs $j]
      set uniqg    [lindex $uniqgs $j]
      set uniqb    [lindex $uniqbs $j]
      if { $r == $uniqr && $g == $uniqg && $b == $uniqb } {
        set found 1
        set foundoneflag 1
        puts "\nmkbothlut: ### found duplicate r,g,b:"
        puts "   1st:   $uniqidnum\t$uniqname\t$uniqr $uniqg $uniqb"
        puts "   dup:   $idnum\t$name\t$r $g $b"
      }
      incr j
    }
    if {!$found} {
      lappend uniqidnums $idnum
      lappend uniqnames  $name
      lappend uniqrs     $r
      lappend uniqgs     $g
      lappend uniqbs     $b
    }
    incr i
  }
  close $id
  if {!$foundoneflag} {
    puts "\nmkbothlut: no duplicate LH/RH colors found"
  } else {
    puts "\nmkbothlut: ### N.B.: duplicates not fixed!"
  }
}

### done
puts "\nmkbothlut: output file $outfile written\n"

