#!/tvbin/tivosh

# TiVo web server written by Stephen Rothwell (sfr@linuxcare.com.au)
# SendKeys Tivo Remote Mod by Jon Squire (jsquire@justice.loyola.edu)
# Note: SendKeys TiVo remote has currently only been tested on a 
# DirecTiVo, but should be fine on others, if a key doesn't work
# look at your sendkeys.tcl file and makesure that the proper key
# is being sent.
#
# Remount added 11/10/2000 1:44am EST but Jon Squire
#
source $tcl_library/tv/log.tcl
source $tcl_library/tv/mfslib.tcl
source $tcl_library/tv/sendkey.tcl

global source_dir
set source_dir [file dirname [info script]]

source $source_dir/util.itcl

proc PrintNames {names} {
    set str ""
    foreach name $names {
        if { [regexp {(.*)\|(.*)} $name junk last first] } {
            if { $str == "" } {
                set str "$first $last"
            } else {
                set str "$str, $first $last"
            }
        }
    }
    return $str
}

proc XMLEncode {str} {
    set return_str ""
    while { [regexp {(.*)\&(.*)} $str junk first last] } {
        set return_str "$return_str$first &amp;"
        set str $last
    }
    set return_str "$return_str$str"
    return $return_str
}

proc ForeachMfsFileTrans { idVar nameVar typeVar dirName prefix count body } {
    global errorInfo errorCode

    upvar $idVar   id
    upvar $nameVar name
    upvar $typeVar type

    # Get the first batch of names
    RetryTransaction {
        if { [catch {mfs scan $dirName -start $prefix -count $count} batch] } {
            global errorCode errorInfo
            if { $errorCode == "errNmNameNotFound" } {
                return
            } else {
                error $batch $errorInfo $errorCode
            }
        }
    }

    set done 0
    while { [llength $batch] > 0 } {
        # Execute the body for each item in this batch
        RetryTransaction {
            foreach item $batch {
                set id   [lindex $item 0]
                set name [lindex $item 1]
                set type [lindex $item 2]

                # bail if we're past the entries that start with the given prefix
                if { ! [PrefixMatches $prefix $name] } {
                    set done 1
                    break
                }

                set code [catch {uplevel $body} string]
                if { $code == 1 } {
                    global errorCode errorInfo
                    if { $errorCode == "errTmActiveLockConflict" ||
                         $errorCode == "errFsLockConflict" } {
                        error $batch $errorInfo $errorCode
                    } else {
                        set done 2
                        break
                    }
                } elseif { $code == 3 } {
                    # this is a break in the body.  just return normally
                    set done 3
                    break
                } elseif { $code != 0 } {
                    set done 4
                    break
                }
            }
        }

        switch -exact $done {
            1 {return}
            2 {return -code error -errorinfo $errorInfo \
                      -errorcode $errorCode $string}
            3 {return}
            4 {return -code $code $string}
        }

        # Get the next batch
        set lastName [lindex [lindex $batch end] 1]
        RetryTransaction {
            set batch [mfs scan $dirName -start $lastName -count $count]
            if { $lastName == [lindex [lindex $batch 0] 1] } {
                set batch [lrange $batch 1 end]
            }
        }
    }
}

proc action_showing {objectid} {
    global db
    global tzoffset
    global cancelreasons
    global selectiontypes
    global states
    global showtypes
    global channeltablestation
    global channeltablenum
    global channeltablecallsign
    global genrenums
    global genrevals
    global tvratingnums
    global tvratingvals
    global tystreams
    global showingbitnums
    global showingbitvals
    global advisorynums
    global advisoryvals
    global mpaaratingnums
    global mpaaratingvals
    global images
    global cache_sp_fsid
    global cache_sp_moddate
    global cache_sp_key

    if {[string index $objectid 0] == "/"} {
        set objectid [string range $objectid 1 end]
    }
    RetryTransaction {
        if { [regexp {([0-9]*)/(.*)} $objectid junk fsid subobjid] } {
            set showing [db $db openidconstruction $fsid $subobjid]
        } else {
            set showing [db $db openid $objectid]
        }
        set rec [dbobj $showing get IndexUsedBy]
        set day [dbobj $showing get Date]
        set time [dbobj $showing get Time]
        set timestr [format "%05d" $time]
        set spfsid [mfs find "/SeasonPass"]
        set spmoddate [mfs moddate $spfsid]
    }
    set recfsid ""
    if { $rec == "" } {
        ForeachMfsFile fsid name type "/Recording/Active" "4:$day:$timestr:" {
            set recfsid $fsid
        }
    }
    if {$spmoddate != $cache_sp_moddate} {
       update_sp_cache $spmoddate
    }
    RetryTransaction {
        if { [regexp {([0-9]*)/(.*)} $objectid junk fsid subobjid] } {
            set showing [db $db openidconstruction $fsid $subobjid]
        } else {
            set showing [db $db openid $objectid]
        }
        set rec [dbobj $showing get IndexUsedBy]
        set station [dbobj $showing get Station]
        set stationid [dbobj $station fsid]
        if { $rec == "" && $recfsid != "" } {
            set rec [db $db openid $recfsid]
            set showing2 [dbobj $rec get Showing]
            set station2 [dbobj $showing2 get Station]
            set stationfsid2 [dbobj $station2 fsid]
            if { $stationid != $stationfsid2 } {
               set rec ""
            } else {
               set showing $showing2
            }
        }
        if { $rec != "" && $recfsid == "" } {
           set recfsid [dbobj $rec fsid]
        }
        set program [dbobj $showing get Program]
        set title [strim [dbobj $program get Title]]
        set series [dbobj $program get Series]
        set seriesfsid ""
        set thumbs ""
        if { $series != "" } {
           set seriesfsid [dbobj $series fsid]
           set score [dbobj $series get ThumbData]
           if { $score != "" } {
              set imagenum [get_thumbimage $score]
              if { $imagenum >= 0} {
                 set imagef [lindex $images $imagenum]
                 set thumbs [img $imagef]
              }
           }
        }
        set episodic 0
        if { $series != "" } {
           set episodic [dbobj $series get Episodic]
        }
        puts "    <Description>[strim [dbobj $program get Description]]</Description>"
        if { $episodic == 1 } {
           set partindex [dbobj $showing get PartIndex]
           set partcount [dbobj $showing get PartCount]
           set partstr ""
           if { $partcount != "" && $partindex != "" } {
              set partstr " ($partindex/$partcount)"
           }
           puts "    <EpisodeTitle>[strim [dbobj $program get EpisodeTitle]]$partstr</EpisodeTitle>\n"
           puts "    <EpisodeNumber>[dbobj $program get EpisodeNum]</EpisodeNumber>\n"
           set altepisodenum [dbobj $program get AltEpisodeNum]
           if { $altepisodenum != "" } {
              puts "    <AltEpisodeNumber>$altepisodenum</AltEpisodeNumber>\n"
           }
        } else {
           puts "    <Year>[dbobj $program get MovieYear]</Year>\n"
        }

        set durationsecs 0
        if { $rec != "" } {
           set stopdate [dbobj $rec get StopDate]
           set stoptime [dbobj $rec get StopTime]
           if { $stoptime == "" } {
              set stoptime [expr [dbobj $showing get Time] + [dbobj $showing get Duration]]
           }
           set startdate [dbobj $rec get StartDate]
           set starttime [dbobj $rec get StartTime]
           if { $starttime == "" } {
              set starttime [dbobj $showing get Time]
           }
           if { $stopdate != "" } {
              set durationsecs [expr ($stopdate * 86400 + $stoptime) - ($startdate * 86400 + $starttime)]
           }
        }
        set showingdurationsecs [dbobj $showing get Duration]
        if { $durationsecs == 0 } {
           set durationsecs $showingdurationsecs
        }
        set duration [format "%d:%02d" [expr $durationsecs / (60*60)] [expr ($durationsecs % (60*60)) / 60]]
        if { [expr $durationsecs - $showingdurationsecs + 90] < 0 } {
           puts "    <Duration>$duration (Partial)</Duration>\n"
        } else {
           puts "    <Duration>$duration</Duration>\n"
        }

        set originalairdate [dbobj $program get OriginalAirDate]
        if { $originalairdate != "" } {
           set originalairdatesecs [expr $originalairdate * 86400]
           set airdatestr [clock format $originalairdatesecs -format "%1m/%1d/%Y"]
           puts "    <OriginalAirDate>$airdatestr</OriginalAirDate>\n"
        }

        if { $rec != "" } {
           set recquality [dbobj $rec get RecordQuality]
           switch -exact $recquality {
              0    { set recqualitystr "Basic" }
              40   { set recqualitystr "Medium" }
              75   { set recqualitystr "High" }
              default  { set recqualitystr "Best" }
           }
           puts "    <Quality>$recqualitystr</Quality>\n"
        }

        set actors [dbobj $program get Actor]
        if { $actors != "" } {
           set actorstr [PrintNames $actors]
           puts "    <Actors>$actorstr</Actors>\n"
        }

        set gueststars [dbobj $program get GuestStar]
        if { $gueststars != "" } {
           set gueststarstr [PrintNames $gueststars]
           puts "    <GuestStars>$gueststarstr</GuestStars>\n"
        }

        set directors [dbobj $program get Director]
        if { $directors != "" } {
           set directorstr [PrintNames $directors]
           puts "    <Directors>$directorstr</Directors>"
        }

        set execproducers [dbobj $program get ExecProducer]
        if { $execproducers != "" } {
           set execproducerstr [PrintNames $execproducers]
           puts "    <ExecProducers>$execproducerstr</ExecProducers>\n"
        }

        set producers [dbobj $program get Producer]
        if { $producers != "" } {
           set producerstr [PrintNames $producers]
           puts "     <Producers>$producerstr</Producers>\n"
        }

        set writers [dbobj $program get Writer]
        if { $writers != "" } {
           set writerstr [PrintNames $writers]
           puts "    <Writers>$writerstr</Writers>]\n"
        }

        set genres [dbobj $program get Genre]
        if { $genres != "" } {
           set genrestr ""
           foreach genre $genres {
              set genreindex [lsearch $genrenums $genre]
              if { $genreindex != -1 } {
                 if { $genrestr != "" } {
                    append genrestr ", "
                 }
                 append genrestr [strim [lindex $genrevals $genreindex]]
              }
           }
           puts "    <Genres>$genrestr</Genres>\n"
        }

        if { $episodic == 1 } {
           set tvrating [dbobj $showing get TvRating]
           if { $tvrating != "" } {
              set tvratingindex [lsearch $tvratingnums $tvrating]
              if { $tvratingindex != -1 } {
                 set tvratingstr [strim [lindex $tvratingvals $tvratingindex]]
              } else {
                 set tvratingstr ""
              }
              puts "    <Rating>$tvratingstr</Rating>\n"
           }
        } else {
           set mpaarating [dbobj $program get MpaaRating]
           if { $mpaarating != "" } {
              set mpaaratingindex [lsearch $mpaaratingnums $mpaarating]
              if { $mpaaratingindex != -1 } {
                 set mpaaratingstr [strim [lindex $mpaaratingvals $mpaaratingindex]]
              } else {
                 set mpaaratingstr ""
              }
              puts "    <Rating>$mpaaratingstr</Rating>\n"
           }
        }

        set showingbits [dbobj $showing get Bits]
        if { $showingbits != "" } {
           set showingbitstr ""
           set index 0
           foreach showingbitnum $showingbitnums {
              if { $showingbitnum & $showingbits } {
                 if { $showingbitstr != "" } {
                    append showingbitstr ", "
                 }
                 append showingbitstr [strim [lindex $showingbitvals $index]]
              }
              incr index
           }
           puts "    <Bits>$showingbitstr</Bits>\n"
        }

        set advisorys [dbobj $program get Advisory]
        if { $advisorys != "" } {
           set advisorystr ""
           foreach advisory $advisorys {
              set advisoryindex [lsearch $advisorynums $advisory]
              if { $advisoryindex != -1 } {
                 if { $advisorystr != "" } {
                    append advisorystr ", "
                 }
                 append advisorystr [strim [lindex $advisoryvals $advisoryindex]]
              }
           }
           puts "    <Advisory>$advisorystr</Advisory>\n"
        }

        if {$rec != ""} {
           if {$seltype == 6} {
              set score [dbobj $rec get Score]
              if {$score != ""} {
                 set dscore [ReadableThumbs $score]
                 puts "    <Score>$dscore</Score>\n"
              }
           }
        }

        set showtype [dbobj $program get ShowType]
        if { $showtype != "" } {
           set showstr [lindex $showtypes [expr $showtype - 1]]
           puts "    <Type>$showstr</Type>\n"
        }

        if { $station != "" } {
           set index [lsearch $channeltablestation $stationid]
           if { $index != -1 } {
              set channum [lindex $channeltablenum $index]
              set callsign [lindex $channeltablecallsign $index]
              puts "    <Channel>$channum</Channel>\n"
              puts "    <CallSign>$callsign</CallSign>\n"
           } else {
              set callsign [dbobj $station get CallSign]
              puts "    <CallSign>$callsign</CallSign>\n"
           }
        }

        set showingstart [expr [dbobj $showing get Date] * 86400 + [dbobj $showing get Time]]
        set showingsecs [expr $showingstart + $tzoffset]
        set timestr [clock format $showingsecs -format "%1m/%1d %l:%M %P"]
        puts "    <ShowingDate>$timestr</ShowingDate>\n"

        if { $rec != "" } {
           set programsource [dbobj $rec get ProgramSource]
           set programsourcefsid ""
           if { $programsource != "" } {
              set programsourcefsid [dbobj $programsource fsid]
           }
           set expirationdate [dbobj $rec get ExpirationDate]
           if { $expirationdate == 0 || $expirationdate == "" || $expirationdate == 24855 } {
              set timestr ""
           } else {
              set expirationsecs [expr $expirationdate * 86400 + [dbobj $rec get ExpirationTime] + $tzoffset]
              set timestr [clock format $expirationsecs -format "%1m/%1d %l:%M %P"]
           }
           puts "    <ExpirationDate>$timestr</ExpirationDate>\n"

           set deletiondate [dbobj $rec get DeletionDate]
           if { $deletiondate == 0 || $deletiondate == "" } {
              set timestr ""
           } else {
              set deletionsecs [expr $deletiondate * 86400 + [dbobj $rec get DeletionTime] + $tzoffset]
              set timestr [clock format $deletionsecs -format "%1m/%1d %l:%M %P"]
           }
           puts "    <DeletionDate>$timestr</DeletionDate>\n"

           set canceldate [dbobj $rec get CancelDate]
           if { $canceldate == 0 || $canceldate == "" } {
              set timestr ""
           } else {
              set cancelsecs [expr $canceldate * 86400 + [dbobj $rec get CancelTime] + $tzoffset]
              set timestr [clock format $cancelsecs -format "%1m/%1d %l:%M %P"]
           }
           puts "    <CancelDate>$timestr</CancelDate>\n"

           set cancelreason [dbobj $rec get CancelReason]
           if { $cancelreason == "" } {
              set cancelstr ""
           } else {
              set cancelstr [lindex $cancelreasons [expr $cancelreason - 1]]
           }
           puts "    <CancelReason>$cancelstr</CancelReason>"

           set errorstring [strim [dbobj $rec get ErrorString]]
           if { $errorstring != "" } {
              while { [set findex [string first "
" $errorstring]] >= 0 } {
                 set errorstring "[string range $errorstring 0 [expr $findex-1]]<BR>[string range $errorstring [expr $findex+1] end]"
              }
              puts "    <ErrorString>$errorstring</ErrorString>\n"
           }

           set bookmark [dbobj $rec get Bookmark]
           if { $bookmark != "" } {
              set timems [expr [dbobj $bookmark get TimeMs] / 1000]
              set timestr [format "%d:%02d:%02d" [expr $timems / (60*60)] [expr ($timems % (60*60)) / 60] [expr $timems % 60]]
              puts "    <Bookmark>$timestr</Bookmark>\n"
           }

           set seltype [dbobj $rec get SelectionType]
           if { $seltype != "" } {
              set seltypestr [lindex $selectiontypes [expr $seltype - 1]]
              puts "    <SelectionType>$seltypestr</SelectionType>\n"
           }

           set state [dbobj $rec get State]
           set statestr [lindex $states [expr $state - 1]]
           puts "    <State>$statestr</State>\n"

           set parts [dbobj $rec get Part]
           if { $state == 3 || $parts == "" } {
              switch -exact $recquality {
                 0    { set bitrate 1630000 }
                 40   { set bitrate 2760000 }
                 75   { set bitrate 3660000 }
                 default  { set bitrate 5960000 }
              }
              set seconds [dbobj $showing get Duration]
              set size "[expr ($seconds * ($bitrate / (8 * 1024))) / 1024] MB (estimated)"
           } else {
              set size 0
              set tystreams ""
              puts "    <Parts>"
              foreach part $parts {
                 set file [dbobj $part get File]
                 put "      <Part>$file</Part>\n"
                 if { [catch {mfs streamsize $file} sizes] } {
                    
                 } else {
                    incr size [expr ([lindex $sizes 0] / 1024) * [lindex $sizes 1] / 1024]
                 }
              }
              append size " MB"
              puts "    </Parts>\n"
           }
           puts "    <Size>$size</Size>"
        }
    }
}

proc action_nowshowing { chan } {
    global db
    global tzoffset
    global images
    global cache_ns_rec
    global cache_ns_series

    ForeachMfsFileTrans fsid name type "/Recording/NowShowing" "" 10 {
        set rec [db $db openid $fsid]
        set seltype [dbobj $rec get SelectionType]
        set showing [dbobj $rec get Showing]
        set showingfsid [dbobj $rec gettarget Showing]
        set station [dbobj $showing get Station]
        set stationid [dbobj $station get CallSign]
        set program [dbobj $showing get Program]
        set title [XMLEncode [strim [dbobj $program get Title]]]
        set seltype [dbobj $rec get SelectionType]
        if { $seltype == 10 || $seltype == 5 } {
            if { $title == "" } {
               set title "Manual Recording"
            } else {
               set title "Manual: $title"
            }
        }
        set episodic 0
        set episode ""
        set series [dbobj $program get Series]
        if { $series != "" } {
           set episodic [dbobj $series get Episodic]
        }
        if { $episodic == 1 } {
           set partindex [dbobj $showing get PartIndex]
           set partcount [dbobj $showing get PartCount]
           set partstr ""
           if { $partcount != "" && $partindex != "" } {
              set partstr " ($partindex of $partcount)"
           }
           set episode [XMLEncode [strim [dbobj $program get EpisodeTitle]]]$partstr
        }

        set seconds [expr [dbobj $showing get Date] * 86400 + [dbobj $showing get Time] + $tzoffset]
        set day [clock format $seconds -format "%a"]
        set date [clock format $seconds -format "%1m/%1d"]
        set expdate [dbobj $rec get ExpirationDate]
        set expsecs [expr $expdate * 86400 + [dbobj $rec get ExpirationTime]]
        set nowsecs [clock seconds]
        set parts [dbobj $rec get Part]
        set totalSize 0
        set tystreams ""
        puts $chan "  <Show>"
        puts $chan "    <Program>$title</Program>"
        puts $chan "    <Day>$day</Day>"
        puts $chan "    <Date>$date</Date>"
        puts $chan "    <Station>$stationid</Station>"
        puts $chan "    <Episode>$episode</Episode>"
        puts $chan "    <fsid>$showingfsid</fsid>"
        puts $chan "    <Parts>"
        foreach part $parts {
            set file [dbobj $part get File]
            puts $chan "      <Part>$file</Part>"
            if { [catch {mfs streamsize $file} sizes] } {
                    
            } else {
                set cbStream [expr ([lindex $sizes 0] / 1024) * [lindex $sizes 1] / 1024]
                puts $chan "      <Size>$cbStream</Size>"
                incr totalSize $cbStream
            }
        }
        puts $chan "    </Parts>"
        puts $chan "    <TotalSize>$totalSize</TotalSize>"
        puts $chan "  </Show>"
    }
}

proc get_tzoffset {mfstz dst} {
   if { $mfstz < 0 } {
      set tz $mfstz
   } else {
      set tzlist "-5 -6 -7 -8 -9 -10 0 1 2 3 4 5 6 7 8 9 10 11 12 -1 -2 -3 -4 -11 -12"
      set tz [lindex $tzlist [expr $mfstz - 1]]
   }
   if { $dst == 2 || $dst == "" } {
      set date [clock format [clock seconds] -format "%1d %u %1m %1H %1M"]
      scan $date "%d %d %d %d %d" dom dow month hour min
      if {$month > 4 && $month < 10} {
         set dlsval 1
      } elseif {$month == 4 && $dom > 7} {
         set dlsval 1
      } elseif {$month == 4 && $dom <= 7 && $dow == 0 && $hour >= 2} {
         set dlsval 1
      } elseif {$month == 4 && $dom <= 7 && $dow != 0 && ($dom-$dow > 0)} {
         set dlsval 1
      } elseif {$month == 10 && $dom < 25} {
         set dlsval 1
      } elseif {$month == 10 && $dom >= 25 && $dow == 0 && $hour < 2} {
         set dlsval 1
      } elseif {$month == 10 && $dom >= 25 && $dow != 0 && ($dom-24-$dow < 1) } {
         set dlsval 1
      } else {
         set dlsval 0
      }
      if {$dlsval == 1} {
         return [expr ($tz+1)*60*60]
      } else {
         return [expr $tz*60*60]
      }
   } else {
      return [expr $tz*60*60]
   }
}

proc GetResourceData { refid startid endid startindex bits } {
   global db

   set keys ""
   set vals ""
   RetryTransaction {
      set sws [db $db open /SwSystem/ACTIVE]
      set offset [expr $refid/65536 - 1]
      set resource [lindex [dbobj $sws get ResourceGroup] $offset]
      set id [dbobj $resource get Id]
      if { $id == $refid } {
         set items [dbobj $resource get Item]
         foreach item $items {
            set id [dbobj $item get Id]
            if { $id >= $startid && $id <= $endid } {
               if { $bits == 1 } {
                  set value [expr 1 << ($id - $startid + $startindex)]
               } else {
                  set value [expr $id - $startid + $startindex]
               }
               set strval [dbobj $item get String]
               if { [string compare $strval "{}"] != 0 } {
                  lappend keys $value
                  lappend vals $strval
               }
            }
         }
      } else {
         puts "Error: refid didn't match"
      }
   }
   return [list $keys $vals]
}

proc init_db {} {
   global db

   global genrenums
   global genrevals
   global tvratingnums
   global tvratingvals
   global showingbitnums
   global showingbitvals
   global advisorynums
   global advisoryvals
   global mpaaratingnums
   global mpaaratingvals

   global tzoffset
   global defrecquality

   global cancelreasons
   global selectiontypes
   global states
   global showtypes

   global images

   RetryTransaction {
      set setup [db $db open /Setup]
      set defrecquality [dbobj $setup get RecordQuality]
      set setuptz [dbobj $setup get TimeZone]
      set daylightsavings [dbobj $setup get DaylightSavingsPolicy]
   }

   set tzoffset [get_tzoffset $setuptz $daylightsavings]

   set cancelreasons "SwitchToLiveTv RecordDifferentShowing StayOnLiveTv InternalError PowerWasOff Expired GotBetterSuggestion DemoMode UnexpectedConflict UserRequestedRecording UserRequestedSeasonPass ExplicitlyDeleted ChannelLineupChanged ProgramGuideChanged RecorderEmergency UserCancelledSeasonPass FuzziesTurnedOff FuzzyStoppedEarly Unknown ProgramSourceConflict ConvertedLiveCache LiveCacheOnlySuccessful ProgramSourceDiskConflict ExplicitlyDeletedFromToDo ProgramSourceModified NotAuthorized NoReRecord NoSignal MaxRecordingsExceeded"
   set selectiontypes "{Show Recommendation} {Package Recommendation} {By Name} {By Channel} Timer {Fuzzy Show} {Fuzzy Package} Bookmark {Season Pass} {Manual Season Pass} Guide IPreview WishListPass Extended"
   set states "{To Do} Cancelled {In Progress} {Now Showing} Deleted {To Do}"
   set showtypes "Serial {Short Film} Special {Limited Series} Series Miniseries {Paid Programming}"

   set images "ExpireNever-256.8.png SelectIcon-256.9.png ThumbUp2-256.8.png ExpireSoon-256.8.png ThumbDn1-256.8.png Expired-256.8.png ThumbDn2-256.8.png ThumbUp3-256.9.png Recording-256.9.png ThumbDn3-256.8.png TivoSuggest-256.8.png SeasonPass.9.png ThumbUp1-256.8.png WishListPass.2.png LargeSquarePredicted3DownThumbs.3.png LargeSquarePredicted2DownThumbs.3.png LargeSquarePredicted1DownThumbs.3.png LargeSquarePredicted1UpThumbs.3.png LargeSquarePredicted2UpThumbs.3.png LargeSquarePredicted3UpThumbs.3.png"

   set genres [GetResourceData 720896 720913 721031 1 0]
   set genrenums [lindex $genres 0]
   set genrevals [lindex $genres 1]

   set tvratings [GetResourceData 983040 983065 983070 1 0]
   set tvratingnums [lindex $tvratings 0]
   set tvratingvals [lindex $tvratings 1]

   set showingbits [GetResourceData 1572864 1572915 1572935 0 1]
   set showingbitnums [lindex $showingbits 0]
   set showingbitvals [lindex $showingbits 1]

   set advisorys [GetResourceData 1048576 1048605 1048614 1 0]
   set advisorynums [lindex $advisorys 0]
   set advisoryvals [lindex $advisorys 1]

   set mpaaratings [GetResourceData 65536 65567 65578 1 0]
   set mpaaratingnums [lindex $mpaaratings 0]
   set mpaaratingvals [lindex $mpaaratings 1]

}

proc connect {host port} {
    variable conn ""

    if [catch {set conn [socket $host $port]} result] {
        puts "$result connecting to $host:$port"
        return 0
    }

    fconfigure $conn -buffering none
    return $conn
} 

global db
set dbPoolSize [expr 100 * 1024]
set db [dbopen $dbPoolSize]
init_db

set chan 0

if { $argc == 2 } {
    set host [lindex $argv 0]
    set port [lindex $argv 1]
    set chan [connect $host $port]
}

if { $chan == 0 } {
    set chan stdout
}
puts $chan "<?xml version=\"1.0\" ?>"
puts $chan "<ShowList>"
action_nowshowing $chan
puts $chan "</ShowList>"
catch { flush $chan }
close $chan
